KEMBAR78
Basics Java | PDF | Object Oriented Programming | Boolean Data Type
0% found this document useful (0 votes)
15 views82 pages

Basics Java

The document provides an overview of Java programming, covering its evolution from consumer electronics to web development and large-scale enterprise applications. It explains key concepts such as classes, objects, object-oriented design, and the phases of Java program execution, including editing, compiling, loading, verifying, and executing. Additionally, it discusses the Java Development Kit (JDK), types of programs, variables, data types, and the use of graphical user interfaces in Java applications.

Uploaded by

Sunith Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views82 pages

Basics Java

The document provides an overview of Java programming, covering its evolution from consumer electronics to web development and large-scale enterprise applications. It explains key concepts such as classes, objects, object-oriented design, and the phases of Java program execution, including editing, compiling, loading, verifying, and executing. Additionally, it discusses the Java Development Kit (JDK), types of programs, variables, data types, and the use of graphical user interfaces in Java applications.

Uploaded by

Sunith Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 82

Java Programming: Basic Concepts

 Originally for intelligent consumer-electronic devices

 Then used for creating Web pages with dynamic


content

Now also used for:


 Develop large-scale enterprise applications

 Enhance WWW server functionality

 Provide applications for consumer devices (cell


phones, etc.)
Classes
• Contain methods that perform tasks
• Return information after task completion
• Used to build Java programs
• Java contains class libraries known as Java APIs
Objects
Reusable software components that model real-world
items
Eg:
People, animals, plants, cars, etc.
Attributes
Size, shape, color, weight, etc.
Behaviors
Babies cry, crawl, sleep, etc
Object-oriented design (OOD)
Models real-world objects
Models communication among objects
Encapsulates data (attributes) and functions (behaviors)
Information hiding
Communication through well-defined interfaces
Object-oriented language
Programming is called object-oriented programming (OOP)
Eg: Java, C++, SmallTalk

Object-Oriented Analysis and Design (OOAD)


Essential for large programs
Analyze program requirements, then develop solution
Object Oriented Programming:

An OOP program models a world of active objects.


An object may have its own “memory,” which may contain other objects.
An object has a set of methods that can process messages of certain
types.
A method can change the object’s state, send messages to other objects,
and create new objects.
An object belongs to a particular class, and the functionality of each object
is determined by its class.
A programmer creates an OOP application by defining classes.

Features of OOP:
Inheritance: a subclass extends a superclass; the objects of a subclass
inherit features of the superclass and can redefine them or add new
features.
Event-driven programs: the program simulates asynchronous handling of
events; methods are called automatically in response to events.
OOP Benefits
• Facilitates team development
• Easier to reuse software components and
write reusable software
• Easier GUI (Graphical User Interface) and
multimedia programming
Java systems contain
Environment
Language
APIs
Class libraries

Java programs normally undergo five phases

Edit
Programmer writes program (and stores
program on disk)
Compile
Compiler creates bytecodes from program
Load
Class loader stores bytecodes in memory
Verify
Verifier ensures bytecodes do not violate
security requirements
Execute
Interpreter translates bytecodes into machine
language
Prog ram is c reated in
Pha se 1 Editor the editor and sto red
Disk
on d isk.

Compiler c rea te s
Pha se 2 bytec odes and stores
Compiler Disk the m on disk.

Primary
Memory
Pha se 3 Class Lo ad er

Class loa de r p uts


byteco des in memory.
Disk ..
..
..

Primary
Memory
Pha se 4 Bytec ode Ve rifier Byte code verifier
confirms that a ll
bytec odes are valid
and do not violate
J ava ’s sec urity
restrictions.
..
..
..

Primary
Memory Interpreter read s
Pha se 5 Interp reter bytec odes and
translates them into a
la nguag e that the
computer can
und ersta nd, possib ly
storing d ata values a s
.. the program executes.
..
..
A Java compiler converts Java source code into instructions for the
Java Virtual Machine.
These instructions, called bytecodes, are the same for any
computer / operating system.
A CPU-specific Java interpreter interprets bytecodes on a particular
computer.
Editor Compiler

 
  
Hello.java Hello.class
 
Interpreter Interpreter

 Hello,
World!


Benefits of two phase execution:

• Platform-independent

• Load from the Internet faster than source code

• Interpreter is faster and smaller than it would


be for Java source

• Source code is not revealed to end users

• Interpreter performs additional security


checks, screens out malicious code
JDK — Java Development Kit
• javac • javadoc
– Java compiler – generates HTML
• java documentation
(“docs”) from source
– Java interpreter
• jar
• appletviewer
– packs classes into jar
– tests applets without a files (packages)
browser

All these are command-line tools, no GUI


Java IDE
• GUI front end for JDK

• Integrates editor, javac, java, appletviewer, debugger,


other tools:
– Specialized Java editor with syntax highlighting,
autoindent, tab setting, etc.
– Clicking on a compiler error message takes you to the
offending source code line

• Usually JDK is installed separately and an IDE is


installed on top of it.
Types of Programs
• Console • GUI applications • Applets
applications
Console Applications
• Simple text dialog:
prompt  input, prompt  input ...  result
C:\javamethods\Ch02> path=%PATH%;C:\Program Files\Java\jdk
1.5.0_07\bin
C:\javamethods\Ch02> javac Greetings2.java
C:\javamethods\Ch02> java Greetings2
Enter your first name: Ramesh
Enter your last name: Tendulkar
Hello, Ramesh Tendulkar
Press any key to continue...
Command-Line Arguments
C:\javamethods\Ch02> javac Greetings.java
C:\javamethods\Ch02> java Greetings Ramesh Tendulkar
Hello, Ramesh Tendulkar

public class Greetings Command-line


{ arguments are
public static void main(String[ ] args) passed to main
{ as an array of
String firstName = args[ 0 ]; Strings.
String lastName = args[ 1 ];
System.out.println("Hello, " + firstName + " " + lastName);
}
}
Command-Line Args (cont’d)
• Can be used in GUI applications, too
• IDEs provide ways to set them (or
prompt for them)

Ramesh Tendulkar
GUI Applications

Menus

Clickable
panel

Buttons Slider
HelloGui.java
import java.awt.*;
import javax.swing.*;
GUI libraries

public class HelloGui extends JFrame


{
< ... other code >

public static void main(String[ ] args)


{
HelloGui window = new HelloGui( );
// Set this window's location and size:
// upper-left corner at 300, 300; width 200, height 100
window.setBounds(300, 300, 200, 100);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
HelloApplet.java
import java.awt.*;
import javax.swing.*;
public class HelloApplet extends JApplet
{
public void init( ) No main in applets: the init
{ method is called by JDK’s
... appletviewer or the browser
}
< ... other code >
}
Introduction to Java Applications

// Welcome1.java
// A first program in Java.

public class Welcome1 {

// main method begins execution of Java application

public static void main( String args[] )


{
System.out.println( "Welcome to Java Programming!" );
} // end method main

} // end class Welcome1


Compiling a program

Open a command prompt window, go to


directory where program is stored

Type javac Welcome1.java

If no errors, Welcome1.class created

Has bytecodes that represent


application

Bytecodes passed to Java


Executing interpreter
a program

Type java Welcome1

Interpreter loads .class file for


class Welcome1
.class extension omitted from
command
Fundamentals of Java Technology

• Reserved Words
– In Java a number of words are reserved for a special
purpose.
– Reserved words use only lowercase letters.
– Reserved words include:
• primitive data types: int, double, char, boolean, etc.
• storage modifiers: public, private, static, final, etc.
• control statements: if, else, switch, while, for, etc.
• built-in constants: true, false, null
– There are about 50 reserved words total.
Programmer-Defined Names

• In addition to reserved words, Java uses standard


names for library packages and classes:
String, Graphics, JFrame, JButton,
java.awt, javax.swing
• The programmer gives names to his or her classes,
methods, fields, and variables.
Variables

• A variable is a “named container”


that holds a value. 5
count
• q = 100 - q;
means:
– 1. Read the current value of q
– 2. Subtract it from 100 mov ax,q
– 3. Move the result back into q mov bx,100
sub bx,ax
mov q,bx
Variables (cont’d)

• Variables can be of different data types: int, char,


double, boolean, etc.
• Variables can hold objects; then the type is the
class of the object.
• The programmer gives names to variables.
• Names of variables usually start with a lowercase
letter.
Variables (cont’d)

• A variable must be declared before it can be


used:

int count;
double x, y; Name(s)
Type JButton go;
Walker amy;
String firstName;
Variables (cont’d)

• The assignment operator = sets the variable’s


value:

count = 5;
x = 0;
go = new JButton("Go");
firstName = args[0];
Variables (cont’d)

• A variable can be initialized in its


declaration:

int count = 5;
JButton go = new JButton("Go");
String firstName = args[0];
Variables: Scope

• Each variable has a scope — the


area in the source code where it is
“visible.”
• If you use a variable outside its
{
scope, the compiler reports a int k = ...;
syntax error. ...
• Variables can have the same }
name when their scopes do not
for (int k = ...)
overlap.
{
...
}
Local Variables

• Local variables are declared inside a constructor


or a method.
• Local variables lose their values and are destroyed
once the constructor or the method is exited.
• The scope of a local variable is from its
declaration down to the closing brace of the block
in which it is declared.
Local Variables (cont’d)

public class SomeClass


{
...
public SomeType SomeMethod (...)
{
Local variable declared Scope

{
Local variable declared
}
}
...
}
Variables (cont’d)

• Common mistakes:

public void someMethod (...)


{
int x = 0;
...
int x = 5; // should be: x = 5;
...
Variable declared twice
within the same scope —
syntax error
Primitive Data Types

• int • byte
• double • short
• char • long
• boolean • float

Used in
Java Methods
Strings

• String is not a primitive data type


• Strings work like any other objects, with two
exceptions:
– Strings in double quotes are recognized as literal constants
– + and += concatenate strings (or a string and a number or an
object, which is converted into a string)

"Catch " + 22 "Catch 22"


Literal Constants

new line

tab

'A', '+', '\n', '\t' char

-99, 2010, 0 int

0.75, -12.3, 8., .5 double

“coin.gif", "1776", "y", "\n" String


Symbolic Constants

• Symbolic constants are initialized final variables:

private final int stepLength = 48;


private static final int BUFFER_SIZE = 1024;
public static final int PIXELS_PER_INCH = 6;
Why Symbolic Constants?

• Easy to change the value throughout the


program, if necessary
• Easy to change into a variable
• More readable, self-documenting code
• Additional data type checking by the compiler
Arithmetic

• Operators: +, -, /, * , %
• The precedence of operators and parentheses is the
same as in algebra
• m % n means the remainder when m is divided by
n (for example, 17 % 5 is 2; 2 % 8 is 2)
• % has the same rank as / and *
• Same-rank binary operators are performed in order
from left to right
Displaying Multiple Lines of Text with a Single Statement

Escape characters
– Backslash ( \ )
– Indicates special characters be output

Escape sequence Description


\n Newline. Position the screen cursor to the beginning of the next
line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters
output after the carriage return overwrite the characters previously
output on that line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
Fig. 2.5 Some common escape sequences.
Displaying Text in a Dialog Box

• Display
– Most Java applications use windows or a dialog box
• We have used command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces
(GUIs)
1 1 // Fig.
Welcome4.java
2.6: Welcome4.java
2 // Printing multiple lines in a dialog box
3 2 // Printing multiple lines in a dialog box
4 3 // Javajavax.swing.JOptionPane;
import extension packages // import class JOptionPane
5 import javax.swing.JOptionPane; // import class JOptionPane
6 4
7 public class Welcome4 {
8 5 public class Welcome4 {
9 // main method begins execution of Java application
6 public static void main( String args] )
10 public static void main( String args[] )
11 7 {
{
12 JOptionPane.showMessageDialog(
13 8 JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );
14
15 9 null, "Welcome\nto\nJava\nProgramming!"
System.exit( 0 ); // terminate application);
1610
17 } // end method main
1811 System.exit( 0 ); // terminate the program
19 } // end class Welcome4
12 }
1 // Fig. 2.9: Addition.java
2 // An addition program.
3
4 // Java extension packages
5 import javax.swing.JOptionPane; // import class JOptionPane
6
7 public class Addition {
8
Declare variables: name and data type.
Input first integer as a String, assign
9 // main method begins execution of Java application
10 to firstNumber.
public static void main( String args[] )
11 {
12 String firstNumber; // first string entered by user
13 String secondNumber; // second string entered by user
14 int number1; // first number to add
15 int number2; // second number to add
16 int sum; // sum of number1 and number2
17
18 // read in first number from user as a String
19 firstNumber =
20 JOptionPane.showInputDialog( "Enter first integer" );
21
22 // read in second number from user as a String
23 secondNumber = Convert strings to integers.
24 JOptionPane.showInputDialog( "Enter second integer" );
25
26 Add,
// convert numbers from type String to place
type result
int in sum.
27 number1 = Integer.parseInt( firstNumber );
28 number2 = Integer.parseInt( secondNumber );
29
30 // add the numbers
31 sum = number1 + number2;
32
33 // display the results
34 JOptionPane.showMessageDialog(
35 null, "The sum is " + sum, "Results",
36 JOptionPane.PLAIN_MESSAGE );
37
38 System.exit( 0 ); // terminate application
39
40 } // end method main
41
42 } // end class Addition
34 JOptionPane.showMessageDialog(
35 null, "The sum is " + sum, "Results",
36 JOptionPane.PLAIN_MESSAGE );

– Different version of showMessageDialog


• Requires four arguments (instead of two as before)
• First argument: null for now
• Second: string to display
• Third: string in title bar
• Fourth: type of message dialog with icon
– Line 36 no icon: JoptionPane.PLAIN_MESSAGE
Message dialog type Icon Description

JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error


to the user.

JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational


message to the user. The user can simply
dismiss the dialog.

JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a


potential problem.

JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to


the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.

JOptionPane.PLAIN_MESSAGE no icon
Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane constants for message dialogs.
Primitive Data Types (size)
Type Size in bits Values Standard
boolean 8 true or false
char 16 ’\u0000’ to ’\uFFFF’ (ISO Unicode character set)
(0 to 65535)
byte 8 –128 to +127
(–27 to 27 – 1)
short 16 –32,768 to +32,767
(–215 to 215 – 1)
int 32 –2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
long 64 –9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
float 32 Negative range: (IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
double 64 Negative range: (IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
Fig. 4.16 The Java primitive data types.
Reading Data from Keyboard
• Console input is by using Scanner that is attached to System.in

/**
@Author ………
*/
import java.util.*;
public class InputTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// get first input
System.out.print("What is your name? ");
String name = in.nextLine();
// get second input
System.out.print("How old are you? ");
int age = in.nextInt();
// display output on console
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
}
}
Functions Defined in Scanner

• java.util.Scanner
– Scanner(InputStream in)
– String nextLine()
– String next()
– int nextInt, double nextDouble()
– boolean hasNext()
– boolean hasNextInt()
– boolean hasNextDouble()

• System.out.printf();
Control Statements

• Java provides three selection structures


– if
– if/else
– switch

• Java provides three repetition structures


– while
– do/while
– do

• Each of these words is a Java keyword


if-else Statement

if ( <condition> ) if ( <condition> )
{ {
< statements > < statements >
} }
else
{
< other statements > else clause
} is optional
boolean Data Type

• boolean variables may have only


two values, true or false.
• You define boolean fields or
boolean local variables the same
way as other variables.
boolean
true
false
private boolean hasMiddleName;
boolean isRolling = false;
Reserved words
Boolean Expressions

• In if (<condition> ) <condition> is a Boolean


expression.
• A Boolean expression evaluates to either true or
false.
• Boolean expressions are written using boolean
variables and relational and logical operators.
Relational Operators

<, >, <=, >=, ==, !=

is equal to

is NOT
equal to
Relational Operators (cont’d)

• Apply to numbers or chars:


if ( count1 <= count2 ) ...
if ( sum != 0 ) ...
if ( letter == 'Y' ) ...
• Do not use == or != with
double x = 7.0;
doubles because they may have double y = 3.5;
rounding errors if (x / y == 2.0)
...

May be
false!
Logical Operators

&&, ||, !

and

or

not
Logical Operators (cont’d)

• ( condition1 && condition2 ) is true if and only


if both condition1 and condition2 are true
• ( condition1 || condition2 ) is true if and only if
condition1 or condition2 (or both) are true
• !condition1 is true if and only if condition1 is
false
Logical Operators (cont’d)

• &&, ||, and ! obey the laws of formal logic called


De Morgan’s Laws:

! (p && q) == ( !p || !q )
! (p || q) == ( !p && !q )
• Example:
if ( ! ( x => -10 && x <= 10 ) ) ...
if ( x < -10 || x > 10 ) ...

Easier to read
Ranks of Operators

Highest
! -(unary) ++ -- (cast)
* / %
+ -
< <= > >= == !=
&&
||
Lowest Easier to read

if ( ( ( year % 4 ) == 0 ) && ( month == 2 ) ) ...


if ( year % 4 == 0 && month == 2 ) ...
Short-Circuit Evaluation

if (condition1 && condition2) ...


If condition1 is false, then condition2 is not
evaluated (the result is false anyway)

if (condition1 || condition2) ...


If condition1 is true, then condition2 is not
evaluated (the result is true anyway)

if ( x >= 0 && Math.sqrt (x) < 15.0) ...

Always OK: won’t get


to sqrt if x < 0
Nested if-else

if ("forward".equals(cmd))
{
if (slide >= numSlides)
beep.play();
else
slide++;
}
else
{
if (slide <= 1)
beep.play();
else
slide--;
}
if-else-if

if (drinkSize.equals(”Large"))
{
price += 1.39;
}
else if (drinkSize.equals("Medium"))
{
price += 1.19;
}
else // if "Small" drink size
{
price += 0.99;
}
The switch
switch (expression)
Statement {
case value1:
...
break;
switch
case case value2:
default ... Don’t
break break; forget
...
... breaks!
Reserved words default:
...
break;
}
The switch Statement (cont’d)

• The same case can have two or more labels. For


example:

switch (num)
{
case 1:
case 2:
System.out.println (“Is Java technology Better");
break;
case 3:
...
}
enum Data Types

• Used when an object’s attribute or state can have


only one of a small set of values,
for example:
private enum Speed { LOW, MEDIUM, HIGH };

private enum InkColor { BLACK, RED };

private enum DayOfWeek { sunday, monday,


tuesday, wednesday, thursday, friday, saturday };
• enum variables do not represent numbers,
characters, or strings.
enum Data Types (cont’d)

• Use == or != to compare enum values


private enum Speed { LOW, MEDIUM, HIGH };
...
Speed currentSpeed = Speed.LOW;
...
if (currentSpeed == Speed.LOW) ...
• Can be used in a switch:
switch (currentSpeed)
{
case LOW:
...
break;
case MEDIUM:
...
Looping Statements
The while Loop
condition is any
logical expression,
while ( condition )
as in if
{
statement1;
statement2; The body of
... the loop
statementN;
}

If the body has only while ( condition )


one statement, the statement1;
braces are optional
The while Loop (cont’d)

• Example:

// Returns the smallest n


// such that 2^n >= x
public static int intLog2 (int x)
{ Initialization
int n = 0, p = 1;
while ( p < x ) Testing
{
p *= 2; Change
n++;
}
return n;
}
The while Loop (cont’d)

• Initialization: The variables tested in the condition


must be initialized to some values. If the
condition is false at the outset, the loop is never
entered.
• Testing: The condition is tested before each
iteration. If false, the program continues with the
first statement after the loop.
• Change: At least one of the variables tested in the
condition must change within the body of the
loop.
The while Loop (cont’d)

• Sometimes change is implicit in the changed state


of a variable:

Scanner input = new Scanner(inputFile);

while (input.hasNext())
System.out.println (input.next());

Changes the
state of input
Loop Invariants

• A loop invariant is an assertion that is true before


the loop and at the end of each iteration.
• Invariants help us reason about the code.

int n = 0, p = 1;
while (p < x) Loop invariant:
{ p = 2n
p *= 2;
n++;
}
...
The for Loop

• for is a shorthand that combines in one statement


initialization, condition, and change:

for ( initialization; condition; change )


{
statement1;
statement2;
...
statementN;
}
The for Loop (cont’d)

• Example:

// Returns the smallest n


// such that 2^n >= x
public static int intLog2 (int x)
{ Initialization
int n = 0, p;
for (p = 1; p < x; p *= 2) Testing
{
n++; Change
}
return n;
}
The for Loop (cont’d)

• Java allows you to declare the loop control


variable in the for statement itself. For example:

for (int i = 0; i < n ; i++)


{
...
}
The scope of i is the
body of the loop, and i
is undefined outside
the loop
The for Loop (cont’d)

• “Repeat n times” idiom:

for (int i = 0; i < n ; i++)


{
...
or }

for (int count = 1; count <= n ; count++)


{
...
}
The for Loop (cont’d)

• Example: n! = 1 * 2 * ... * n

/**
* Returns 1 * 2 * ... * n, if n >= 1 (and 1 otherwise)
*/
public static long factorial (int n)
{
long f = 1;

for (int k = 2; k <= n; k++)


f *= k;

return f;
}
The do-while Loop

do The code runs


{ through the body of
statement1; the loop at least
statement2; once
...
statementN; if condition is false,
} while ( condition ); the next iteration is
not executed
Always use braces
for readability (even
if the body has only
one statement)
The do-while Loop (cont’d)

• do-while is convenient when the variables tested


in the condition are calculated or read in the body
of the loop:

String str;

do
{
str = file.readLine();
...
} while (str != null);
The do-while Loop (cont’d)

• do-while can be easily avoided: we can usually


replace it with a while loop initialized so that it
goes through the first iteration:

String str = "dummy";

while (str != null)


{
str = file.readLine();
...
}
break and return in Loops

• break in a loop instructs the program to


immediately quit the current iteration and go to the
first statement following the loop.
• return in a loop instructs the program to
immediately quit the current method and return to
the calling method.
• A break or return must be inside an if or an else,
otherwise the code after it in the body of the loop
will be unreachable.
break in Loops

• Example:
int d = n - 1;

while (d > 0)
{
if (n % d == 0)
break;
d--;
}

if ( d > 0 ) // if found a divisor


...
return in Loops

• Sequential Search method:

public int search(String[ ] list, String word)


{
for (int k = 0; k < list.length; k++)
{
if (list[k].equals (word)
return k;
}

return -1;
}
// Class average program with counter-controlled repetition.
import javax.swing.JOptionPane;
public class Average1 {
public static void main( String args[] )
{
int total, gradeCounter, gradeValue, average;
String grade;
// Initialization Phase
total = 0; // clear total
gradeCounter = 1; // prepare to loop
while ( gradeCounter <= 10 ) { // loop 10 times
// prompt for input and read grade from user
grade = JOptionPane.showInputDialog("Enter integer grade: " );
// convert grade from a String to an integer
gradeValue = Integer.parseInt( grade );
total = total + gradeValue;
gradeCounter = gradeCounter + 1;
}
// Termination Phase
average = total / 10; // perform integer division
// display average of exam grades
JOptionPane.showMessageDialog( null,
• "Class average is " + average, "Class Average",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 ); // terminate the program
} // end method main
} // end class Average1
Lab Assignment
To find the first four perfect numbers.
• A perfect number is a positive integer equal to the sum of all its divisors (including 1 but
excluding the number itself). For example:
28 = 1 + 2 + 4 + 7 + 14

To generate prime numbers from 1 to n


To simulate simple calculator
To evaluate sin, cosine, tan series

To generate Fibonacci series

To search for a number in the list of numbers


Numbers are to be passed as command line entries.
To find the max. & min. in the list of numbers
Numbers are to be passed as command line entries.

You might also like