0% found this document useful (0 votes)
4 views

[5] Programming Language Fundamentals (Part 2)

The document explains the fundamentals of defining programmer-defined classes in Java, emphasizing the need for custom classes to meet application requirements. It provides examples of class definitions, constructors, and methods, specifically using a Bicycle class and an Account class to illustrate object-oriented programming concepts. Additionally, it covers topics such as memory allocation, visibility modifiers, and the importance of information hiding in class design.

Uploaded by

denoircaera07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

[5] Programming Language Fundamentals (Part 2)

The document explains the fundamentals of defining programmer-defined classes in Java, emphasizing the need for custom classes to meet application requirements. It provides examples of class definitions, constructors, and methods, specifically using a Bicycle class and an Account class to illustrate object-oriented programming concepts. Additionally, it covers topics such as memory allocation, visibility modifiers, and the importance of information hiding in class design.

Uploaded by

denoircaera07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 98

PROGRAMMING

LANGUAGE
FUNDAMENTALS
1
2 DEFINING YOUR OWN
CLASSES
WHY PROGRAMMER-
DEFINED CLASSES?
 Using just the String, GregorianCalendar,
JFrame and other standard classes will not
meet all of our needs. We need to be able to
define our own classes customized for our
applications.
 Learning how to define our own classes is the
first step toward mastering the skills necessary
in building large programs.
 Classes we define ourselves are called
programmer-defined classes.

3
EXAMPLE 1: USING THE
Bicycle CLASS
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2;
String owner1, owner2;

bike1 = new Bicycle( ); //Create and assign values to bike1


bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( ); //Create and assign values to bike2


bike2.setOwnerName("Ben Jones");

owner1 = bike1.getOwnerName( ); //Output the information


owner2 = bike2.getOwnerName( );

System.out.println(owner1 + " owns a bicycle.");

System.out.println(owner2 + " also owns a bicycle.");


}
}
THE DEFINITION OF THE
Bicycle CLASS
class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member
public void Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
}
MULTIPLE INSTANCES
 Once the Bicycle class is defined, we can
create multiple instances.
bike1 bike2

Bicycle bike1, bike2;

: Bicycle : Bicycle
bike1 = new Bicycle( );
bike1.setOwnerName("Adam Smith");
ownerName ownerName

bike2 = new Bicycle( ); “Adam “Ben Jones”


Smith”
bike2.setOwnerName("Ben Jones");

Sample Code
6
THE PROGRAM STRUCTURE
AND SOURCE FILES
BicycleRegistration Bicycle

There
Therearearetwo
twosource
source
files. Each class
files. Each class
definition
definitionisisstored
storedin
inaa
BicycleRegistration.java Bicycle.java separate
separatefile.
file.

To run the program: 1. javac Bicycle.java (compile)


2. javac BicycleRegistration.java (compile)
3. java BicycleRegistration (run)
CLASS DIAGRAM FOR
Bicycle
Bicycle

Bicycle( )
Method
MethodListing
Listing
We
We list the nameand
list the name andthe
the
getOwnerName( )
data type of an
data type of an
argument
argumentpassed
passedtotothe
the
setOwnerName(String) method.
method.
TEMPLATE FOR CLASS
DEFINITION
Import
Import
Statements
Statements

Class
ClassComment
Comment

class { Class
ClassName
Name

Data
DataMembers
Members

Methods
Methods
(incl.
(incl.Constructor)
Constructor)

}
DATA MEMBER
DECLARATION
<modifiers> <data type> <name> ;

Modifier
Modifier Data
Data Type
Type Name
Name
ss

private String
ownerName ;

Note:
Note:There’s
There’sonly
onlyone
onemodifier
modifierin
inthis
this
example.
example.
METHOD DECLARATION
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}

Modifie
Modifie Return
Return Method
Method Parameter
Parameter
rr Type
Type Name
Name

public void setOwnerName ( String


name ) {
Statements
Statements
ownerName = name;
}
CONSTRUCTOR
 A constructor is a special method that is
executed when a new instance of the class is
created.
public <class name> ( <parameters> )
{
<statements>
}
Modifier
Modifier Class
ClassName
Name Parameter
Parameter

public Bicycle ( ) {
ownerName = "Unassigned";
}
Statements
Statements
EXAMPLE 2: USING Bicycle
AND Account
class SecondMain {
//This sample program uses both the Bicycle and Account classes
public static void main(String[] args) {
Bicycle bike;
Account acct;
String myName = "Jon Java";
bike = new Bicycle( );
bike.setOwnerName(myName);
acct = new Account( );
acct.setOwnerName(myName);
acct.setInitialBalance(250.00);
acct.add(25.00);
acct.deduct(50);
//Output some information
System.out.println(bike.getOwnerName() + " owns a bicycle and");
System.out.println("has $ " + acct.getCurrentBalance() +
" left in the bank");
}
}
THE Account CLASS
class Account {
private String ownerName; public void setInitialBalance
(double bal) {
private double balance;
balance = bal;
public Account( ) { }
ownerName = "Unassigned";
balance = 0.0; public void setOwnerName
} (String name) {
public void add(double amt) { ownerName = name;
balance = balance + amt; }
} }
public void deduct(double amt) {
balance = balance - amt;
}
public double getCurrentBalance( ) {
return balance;
}
public String getOwnerName( ) {
return ownerName;
}

Page 1 Page 2
THE PROGRAM STRUCTURE
FOR SecondMain Bicycle
SecondMain

Account

SecondMain.java Bicycle.java Account.java

Note: You only


Note: You only
To run the program: 1. javac Bicycle.java (compile) need
needtoto
2. javac Account.java (compile)
compile
compilethe
the
2. javac SecondMain.java (compile)class once.
class once.
Recompile
Recompileonly
only
3. java SecondMain (run) when you made
when you made
changes
changesin
inthe
the
code.
code.
ARGUMENTS AND
PARAMETERS
class Sample {
class Account { parameter
public static void
main(String[] arg) { . . .

Account acct = new Account(); public void add(double amt) {


. . .
balance = balance + amt;
acct.add(400); }
. . .
} . . .
}
. . . argument
}

 An argument is a value we pass to a method.


 A parameter is a placeholder in the called method
to hold the value of the passed argument.
MATCHING ARGUMENTS AND
PARAMETERS
 The number or
Demo demo = new Demo( );
arguments and the
parameters must be
int i = 5; int k = 14;
the same.
demo.compute(i, k, 20);
3 arguments
 Arguments and
Passing Side parameters are
paired left to right

class Demo {  The matched pair


public void compute(int i, int j, double x) {
. . .
must be
}
3 parameters assignment-
}
compatible (e.g.
you cannot pass a
Receiving Side double argument to
a int parameter)
MEMORY ALLOCATION
 Separate memory
space is allocated
i 5 i 5 for the receiving
method.
k 14 j 14

20 x 20.0
 Values of
arguments are
Passing Side Receiving Side passed into
memory
Literal constant
has no name
allocated for
parameters.
PASSING OBJECTS TO A
METHOD
 As we can pass int and double values, we can
also pass an object to a method.
 When we pass an object, we are actually
passing the reference (name) of an object.
− It means a duplicate of an object is NOT
created in the called method.

19
PASSING A Student OBJECT
1
LibraryCard card2; student st
card2 = new LibraryCard();
card2.setOwner(student);
card2

Passing Side 1
class LibraryCard {
private Student owner;
2
public void setOwner(Student st) {

}
owner = st;
2 :
LibraryCard
:
Student
}
owner name
Receiving Side “Jon Java”

borrowCnt email
1 Argument is passed 0 “jj@javauniv.ed
u”
2 Value is assigned to the
data member State of Memory 20
SHARING AN OBJECT

 We pass the same Student


object to card1 and card2

• Since we are actually


passing a reference to the
same object, it results in
owner of two LibraryCard
objects pointing to the
same Student object

21
INFORMATION HIDING AND
VISIBILITY MODIFIERS
 The modifiers public and private designate
the accessibility of data members and methods.
 If a class component (data member or method)
is declared private, client classes cannot access
it.
 If a class component is declared public, client
classes can access it.
 Internal details of a class are declared private
and hidden from the clients. This is
information hiding.

22
ACCESSIBILITY EXAMPLE

… class Service {
public int memberOne;
Service obj = new Service();
private int memberTwo;
public void doOne() {
obj.memberOne = 10;

obj.memberTwo = 20; }
private void doTwo() {
obj.doOne(); …
}
obj.doTwo(); }

Client Service 23
DATA MEMBERS SHOULD BE
PRIVATE
 Data members are the implementation details
of the class, so they should be invisible to the
clients. Declare them private .
 Exception: Constants can (should) be declared
public if they are meant to be used directly by
the outside methods.

24
GUIDELINE FOR VISIBILITY
MODIFIERS
 Guidelines in determining the visibility of data
members and methods:
Declare the class and instance variables
private.
Declare the class and instance methods
private if they are used only by the other
methods in the same class.
Declare the class constants public if you want
to make their values directly readable by the
client programs. If the class constants are
used for internal purposes only, then declare
them private.
25
DIAGRAM NOTATION FOR
VISIBILITY

public – plus symbol (+)


private – minus symbol (-)

26
CLASS CONSTANTS
 We illustrate the use of constants in
programmer-defined service classes here.
 Remember, the use of constants
− provides a meaningful description of what the
values stand for. number = UNDEFINED; is more
meaningful than number = -1;
− provides easier program maintenance. We only
need to change the value in the constant
declaration instead of locating all occurrences of
the same value in the program code

27
A SAMPLE USE OF
CONSTANTS
import java.util.Random;
class Die {

private static final int MAX_NUMBER = 6;


private static final int MIN_NUMBER = 1;
private static final int NO_NUMBER = 0;

private int number;


private Random random;

public Dice( ) {
random = new Random();
number = NO_NUMBER;
}

//Rolls the dice


public void roll( ) {
number = random.nextInt(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER;
}

//Returns the number on this dice


public int getNumber( ) {
return number;
}
}
28
LOCAL VARIABLES
 Local variables are declared within a method
declaration and used for temporary services,
such as storing intermediate computation
results.
public double convert(int num) {

double result; local variable

result = Math.sqrt(num * num);

return result;
}

29
LOCAL, PARAMETER, AND
DATA MEMBER
 An identifier appearing inside a method can be
a local variable, a parameter, or a data
member.
 The rules are:
− If there’s a matching local variable declaration or
a parameter, then the identifier refers to the local
variable or the parameter.
− Otherwise, if there’s a matching data member
declaration, then the identifier refers to the data
member.
− Otherwise, it is an error because there’s no
matching declaration.

30
SAMPLE MATCHING
class MusicCD {

private String artist;


private String title;
private String id;

public MusicCD(String name1, String name2) {

String ident;

artist = name1;

title = name2;

ident = artist.substring(0,2) + "-" +

title.substring(0,9);

id = ident;
}
31
...
}
CALLING METHODS OF THE
SAME

CLASS
So far, we have been calling a method of
another class (object).
 It is possible to call method of a class from
another method of the same class.
− in this case, we simply refer to a method without
dot notation

32
CHANGING ANY CLASS TO A
MAIN

CLASS
Any class can be set to be a main class.
 All you have to do is to include the main
method.
class Bicycle {

//definition of the class as shown before comes here

//The main method that shows a sample


//use of the Bicycle class
public static void main(String[] args) {

Bicycle myBike;

myBike = new Bicycle( );


myBike.setOwnerName("Jon Java");

System.out.println(myBike.getOwnerName() + "owns a bicycle");


}
}

33
34 SELECTION
STATEMENTS
THE if STATEMENT
int testScore;

testScore = //get test score input

if (testScore < 70)


This
Thisstatement
statementisis
System.out.println("You did not pass" ); executed
executedififthe
the
testScore
testScore is lessthan
is less than
else 70.
70.

This
Thisstatement
statementisis
System.out.println("You did pass" ); executed
executedififthe
the
testScore
testScore is 70or
is 70 or
higher.
higher.
SYNTAX FOR THE if
STATEMENT
if ( <boolean expression> )

<then block>
else

Boolean
Boolean
<else block>
Expression
Expression

if ( testScore < 70 )

Then
Then System.out.println("You did not pass");
Block
Block
else

Else
Else Block
Block System.out.println("You did pass ");
CONTROL FLOW
false testScore
true
testScore
<70
<70??

System.out.println
System.out.println System.out.println
System.out.println
("You
("Youdid
didpass");
pass"); ("You
("Youdid
didnot
notpass");
pass");
RELATIONAL OPERATORS
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to

testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
COMPOUND STATEMENTS
 Use braces if the <then> or <else> block has
multiple statements.
if (testScore < 70)
{
System.out.println("You did not pass“ ); Then
Then
System.out.println(“Try harder next time“ ); Block
Block
}
else
{
System.out.println(“You did pass“ );
System.out.println(“Keep up the good work“ ); Else
Else Block
Block
}

39
STYLE GUIDE
if ( <boolean expression> ) {

} else {
… Style
Style 11
}

if ( <boolean expression> )
{

} Style
Style 22
else
{

}
THE if-then BLOCK
if ( <boolean expression> )

<then block>

Boolean
Boolean
Expression
Expression

if ( testScore >= 95 )

Then System.out.println("You are an honor student");


Then Block
Block
CONTROL FLOW OF if-then

testScore
true
testScore
>=95?
>=95?

System.out.println
System.out.println((
"You
"Youare
arean
anhonor
honorstudent");
false student");
THE NESTED if STATEMENT
 The then and else block of an if statement can
contain any valid statements, including other if
statements. An if statement containing another
if statement is called a nested-if statement.

if (testScore >= 70) {


if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >=
70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
CONTROL FLOW OF NESTED
if STATEMENT
false true inner if
testScore
testScore>=
>=
70
70??

System.out.printl false studentAge true


System.out.printl studentAge<<10
10
nn ??
("You
("Youdid
didnot
notpass");
pass");

System.out.printl
System.out.printl System.out.println
nn System.out.println
("You
("Youdid
didaagreat
greatjob");
job");
("You
("Youdid
didpass");
pass");
WRITING A PROPER if
CONTROL
if (num1 < 0) negativeCount = 0;
if (num2 < 0)
if (num3 < 0)
negativeCount = 3; if (num1 < 0)
else negativeCount++;
negativeCount = 2;
if (num2 < 0)
else
if (num3 < 0)
negativeCount++;
negativeCount = 2; if (num3 < 0)
else negativeCount++;
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1;
The
Thestatement
statement
else
if (num3 < 0)
negativeCount = 1;
negativeCount++;
negativeCount++;
else
negativeCount = 0; increments
incrementsthe
thevariable
variableby
by
one
one
if-else-if CONTROL
if (score >= 90)
System.out.print("Your grade is A");

else if (score >= 80)


Test Score Grade System.out.print("Your grade is B");
90  score A
else if (score >= 70)
80  score  90 B System.out.print("Your grade is C");

70  score  80 C else if (score >= 60)


60  score  70 D System.out.print("Your grade is D");

score  60 F else
System.out.print("Your grade is F");
MATCHING else
Are A
A and B
B different?

if (x < y) A
A Both A
A and B
B means…
if (x < z)
System.out.print("Hello"); if (x < y) {
else if (x < z) {
System.out.print("Good bye"); System.out.print("Hello");
} else {
System.out.print("Good
bye");
}
if (x < y) B
B }
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");
BOOLEAN OPERATORS
 A boolean operator takes boolean values as
its operands and returns a boolean value.
 The three boolean operators are
− and: &&
− or: ||
− not !

if (temperature >= 65 && distanceToDestination < 2) {


System.out.println("Let's walk");
} else {
System.out.println("Let's drive");
}
SEMANTICS OF BOOLEAN
OPERATORS

Boolean operators and their meanings:

P Q P && P || Q !P
Q
false false false false true
false true false true true
true false false true false
true true true true false
DE MORGAN’S LAW
 De Morgan's Law allows us to rewrite boolean
expressions in different ways:

Rule 1: !(P && Q)  !P || !Q

Rule 2: !(P || Q)  !P && !Q

!(temp >= 65 && dist < 2)

 !(temp >=65) || !(dist < 2) by Rule 1

 (temp < 65 || dist >= 2)


SHORT-CIRCUIT EVALUATION
 Consider the following boolean expression:
x > y || x > z
 The expression is evaluated left to right. If x > y
is true, then there’s no need to evaluate x > z
because the whole expression will be true
whether x > z is true or not.
 To stop the evaluation once the result of the
whole expression is known is called short-
circuit evaluation.
 What would happen if the short-circuit
evaluation is not done for the following
expression?
z == 0 || x / z > 20
OPERATOR PRECEDENCE
RULE
BOOLEAN VARIABLES
 The result of a boolean expression is either
true or false. These are the two values of data
type boolean.
 We can declare a variable of data type boolean
and assign a boolean value to it.
boolean pass, done;
pass = 70 < x;
done = true;
if (pass) {

} else {

}
BOOLEAN METHODS
 A method that returns a boolean value, such as

private boolean isValid(int value) {


if (value < MAX_ALLOWED)
return true;
} else {
return false;
}
}

if (isValid(30)) {

Can be used as } else {

}
COMPARING OBJECTS
 With primitive data types, we have only one
way to compare them, but with objects
(reference data type), we have two ways to
compare them.
1. We can test whether two variables point to
the same object (use ==), or
2. We can test whether two distinct objects
have the same contents.
USING == WITH OBJECTS
(SAMPLE 1)
String str1 = new String("Java");
String str2 = new String("Java");

if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

Not equal because


They are not equal str1 and str2 point to
different String
objects.
USING == WITH OBJECTS
(SAMPLE 2)
String str1 = new String("Java");
String str2 = str1;

if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

It's equal here


They are equal because str1 and
str2 point to the
same object.
USING equals WITH STRING
String str1 = new String("Java");
String str2 = new String("Java");

if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

It's equal here


They are equal
because str1 and
str2 have the same
sequence of
characters.
THE SEMANTICS OF ==
IN CREATING STRING
OBJECTS
THE switch STATEMENT
Scanner scanner = new Scanner(System.in);

System.out.println( "Grade (Frosh-1,Soph-2,...):“);


int gradeLevel = scanner.nextInt(); This
This
switch (gradeLevel) { statement
statementisis
executed
executedifif
case 1: System.out.print("Go to the Gymnasium");
the
the
break; gradeLevel
gradeLevelisis
equal
equalto
to1.
1.
case 2: System.out.print("Go to the Science Auditorium");
break;

case 3: System.out.print("Go to Harris Hall Rm A3");


break;
This
This
statement
statementisis
case 4: System.out.print("Go to Bolt Hall Rm 101");
executed
executedifif
break; the
the
} gradeLevel
gradeLevelisis
equal
equalto
to4.
4.
SYNTAX FOR THE switch
STATEMENT
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>

<case label n> : <case body n>
}
Arithmetic
Arithmetic
Expression
Expression
switch ( gradeLevel ) {
case 1: System.out.print( "Go to the Gymnasium" );
break;
Case
Case case 2: System.out.print( "Go to the Science Auditorium" );
Label
Label break;
case 3: System.out.print( "Go to Harris Hall Rm A3" ); Case
break;
Case
Body
Body
case 4: System.out.print( "Go to Bolt Hall Rm 101" );
break;
}
switch WITH NO break
STATEMENTS
true
NN
==1 xx==10;
10;
switch ( N ) { ==1??

case 1: x = 10; false


case 2: x = 20; true
NN
xx==20;
case 3: x = 30; ==2
==2?? 20;

} false
true
NN
xx==30;
30;
==3
==3??

false
switch WITH break
STATEMENTS
true
NN
switch ( N ) { ==1 xx==10;
10;
==1??
case 1: x = 10;
false break;
break;
break; true
case 2: x = 20; NN
==2 xx==20;
20;
==2??
break;
case 3: x = 30; false break;
break;
true
break; NN
==3 xx==30;
30;
} ==3??

false break;
break;
switch WITH THE default
BLOCK
switch (ranking) {

case 10:
case 9:
case 8: System.out.print("Master");
break;

case 7:
case 6: System.out.print("Journeyman");
break;

case 5:
case 4: System.out.print("Apprentice");
break;

default: System.out.print("Input error: Invalid Data");


break;
}
66 REPETITION
STATEMENTS
DEFINITION
 Repetition statements control a block of code to
be executed for a fixed number of times or until
a certain condition is met.
 Count-controlled repetitions terminate the
execution of the block after it is executed for a
fixed number of times.
 Sentinel-controlled repetitions terminate
the execution of the block after one of the
designated values called a sentinel is
encountered.
 Repetition statements are called loop
statements also.
THE while STATEMENT
int sum = 0, number = 1;

while ( number <= 100 ) {

sum = sum + number; These


Thesestatements
statementsareare
executed as long as
executed as long as
number
numberisisless
lessthan
than
number = number + 1; or equal to 100.
or equal to 100.

}
SYNTAX FOR THE while
STATEMENT
while ( <boolean expression> )

<statement>

Boolean
Boolean
Expression
Expression

while ( number <= 100 ) {

Statemen
Statemen sum = sum + number;
tt
(loop
(loop number = number + 1;
body)
body)
}
CONTROL FLOW OF while

int
intsum
sum==0,
0,number
number==11

number
number<=
<=100
100
true
??

false sum
sum=
=sum
sum+
+
number;
number;

number
number==number
number++
1;
1;
MORE EXAMPLES
Keeps
Keepsadding
addingthe
11 int sum = 0, number = 1; numbers
the
numbers 1, 2, 3,…
1, 2, 3, …
until the sum
until the sum
while ( sum <= 1000000 ) { becomes
becomeslarger
largerthan
than
sum = sum + number; 1,000,000.
1,000,000.
number = number + 1;
}

22 int product = 1, number = 1, Computes


Computesthethe
count = 20, lastNumber;
product
product of thefirst
of the first20
20
odd integers.
odd integers.
lastNumber = 2 * count - 1;

while (number <= lastNumber) {


product = product * number;
number = number + 2;
}
EXAMPLE: TESTING INPUT
DATA
int age; Priming
Priming Read
Read
Scanner scanner = new Scanner(System.in);

System.out.print("Your Age (between 0 and 130): ");


age = scanner.nextInt( );

while (age < 0 || age > 130) {

System.out.println(
"An invalid age was entered. Please try again.");

System.out.print("Your Age (between 0 and 130): ");

age = scanner.nextInt( );
}
USEFUL SHORTHAND
OPERATORS
sum = sum + number; is equivalent sum +=
to number;

Operator Usage Meaning


+= a += b; a = a + b;
-= a -= b; a = a – b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
WATCH OUT FOR PITFALLS
1. Watch out for the off-by-one error (OBOE).
2. Make sure the loop body contains a statement
that will eventually cause the loop to
terminate.
3. Make sure the loop repeats exactly the correct
number of times.
4. If you want to execute the loop body N times,
then initialize the counter to 0 and use the
test condition counter < N or initialize the
counter to 1 and use the test condition
counter <= N.
LOOP PITFALL - 1
11 int product = 0;

while ( product < 500000 ) {


product = product * 5;
}

Infinite
Infinite Loops
Loops
Both
Bothloops
loopswill
willnot
not
terminate because
terminate because
the
theboolean
boolean
22 int count = 1; expressions
expressionswill
never
will
never becomefalse.
become false.
while ( count != 10 ) {
count = count + 2;
}
OVERFLOW
 An infinite loop often results in an overflow
error.
 An overflow error occurs when you attempt to
assign a value larger than the maximum value
the variable can hold.
 In Java, an overflow does not cause program
termination. With types float and double, a
value that represents infinity is assigned to the
variable. With type int, the value “wraps
around” and becomes a negative value.
LOOP PITFALL - 2
11 float count = 0.0f;

while ( count != 1.0f ) {


count = count + 0.3333333f;
} //seven 3s
Using
Using Real
Real
Numbers
Numbers
Loop
Loop22terminates,
terminates,but
but
Loop 1 does not because
Loop 1 does not because
only
onlyan
anapproximation
approximationofof
aareal number can be
22 float count = 0.0f; real number can be
stored
storedininaacomputer
computer
memory.
memory.
while ( count != 1.0f ) {
count = count + 0.33333333f;
} //eight 3s
LOOP PITFALL – 2A
11 int result = 0; double cnt = 1.0;
while (cnt <= 10.0){
cnt += 1.0;
result++;
}
System.out.println(result); Using
Using Real
Real
10 Numbers
Numbers
Loop
Loop11prints
printsout
out10,
10,as
as
expected, but Loop
expected, but Loop 2 2
prints
printsout
out11.
11.The
Thevalue
value
0.1 cannot be stored
0.1 cannot be stored
22 int result = 0; double cnt = 0.0; precisely
preciselyin
incomputer
computer
while (cnt <= 1.0){ memory.
memory.
cnt += 0.1;
result++;
}
System.out.println(result);

11
LOOP PITFALL – 3
 Goal: Execute the loop body 10 times.

11 count = 1; 22 count = 1;
while ( count < 10 ){ while ( count <= 10 ){
. . . . . .
count++; count++;
} }

33 count = 0; 44 count = 0;
while ( count <= 10 ){ while ( count < 10 ){
. . . . . .
count++; count++;
} }

11 and 33 exhibit off-by-one error.


THE do-while STATEMENT
int sum = 0, number = 1;

do {

sum += number; These


Thesestatements
statementsare are
executed as long
executed as long asas
number++; sum
sumisisless
lessthan
thanoror
equal to 1,000,000.
equal to 1,000,000.

} while ( sum <= 1000000 );


SYNTAX FOR THE do-while
STATEMENT
do
<statement>

while ( <boolean expression> ) ;

do {

Statemen
Statemen
sum += number; tt
number++; (loop
(loop
body)
body)
} while ( sum <=
1000000 );

Boolean
Boolean
Expression
Expression
CONTROL FLOW OF do-
while
int
intsum
sum==0,
0,number
number==11

sum
sum+=
+=number;
number;

number++;
number++;

sum
sum<=
<=
true
1000000
1000000??

false
LOOP-AND-A-HALF
REPETITION

CONTROL
Loop-and-a-half repetition control can be
used to test a loop’s terminating condition in
the middle of the loop body.

 It is implemented by using reserved words


while, if, and break.
EXAMPLE: LOOP-AND-A-
HALF CONTROL
String name;
Scanner scanner = new Scanner(System.in);

while (true){
System.out.print("Your name“);
name = scanner.next( );

if (name.length() > 0) break;

System.out.println("Invalid Entry." +
"You must enter at least one character.");
}
PITFALLS FOR LOOP-AND-A-
HALF

CONTROL
Be aware of two concerns when using the loop-
and-a-half control:
− The danger of an infinite loop. The
boolean expression of the while statement is
true, which will always evaluate to true. If we
forget to include an if statement to break out
of the loop, it will result in an infinite loop.

− Multiple exit points. It is possible, although


complex, to write a correct control loop with
multiple exit points (breaks). It is good
practice to enforce the one-entry one-exit
control flow.
THE for STATEMENT
int i, sum = 0, number;

for (i = 0; i < 20; i++) {

number = scanner.nextInt( );
sum += number;

These
Thesestatements
statementsare are
executed for 20 times
executed for 20 times
((i i==0,
0,1,
1,2,
2,……, ,19).
19).
SYNTAX FOR THE for
STATEMENT
for ( <initialization>; <boolean expression>; <increment> )

<statement>

Initializatio
Initializatio Boolean
Boolean Increment
Increment
nn Expression
Expression

for ( i = 0 ; i < 20 ; i++ ) {


Statemen
Statemen
number = scanner.nextInt(); tt
sum += number; (loop
(loop
} body)
body)
CONTROL FLOW OF for
ii =
= 0;
0;

ii <
< 20
20 ??
false
true
number
number =
=......;;
sum
sum +=
+=number;
number;

ii ++;
++;
MORE for LOOP EXAMPLES
11 for (int i = 0; i < 100; i += 5)
ii =
= 0,
0, 5,
5, 10,
10, …
… ,,
95
95

22 for (int j = 2; j < 40; j *= 2)


jj =
= 2,
2, 4,
4, 8,
8, 16,
16,
32
32

33 for (int k = 100; k > 0; k--) )


kk =
= 100,
100, 99,99, 98,
98,
97,
97, ...,
..., 11
THE NESTED-for
STATEMENT
 Nesting a for statement inside another for
statement is commonly used technique in
programming.
 Let’s generate the following table using nested-
for statement.
GENERATING THE TABLE
int price;
for (int width = 11; width <=20, width++){

for (int length = 5, length <=25, length+=5){

price = width * length * 19; //$19 per sq. ft.


INNER
OUTER

System.out.print (" " + price);


}
//finished one row; move on to next row
System.out.println("");
}
FORMATTING OUTPUT
 We call the space occupied by an output value
the field. The number of characters allocated
to a field is the field width. The diagram shows
the field width of 6.
 From Java 5.0, we can use the Formatter class.
System.out (PrintStream) also includes the
format method.
THE Formatter CLASS
 We use the Formatter class to format the
output.
 First we create an instance of the class

Formatter formatter = new Formatter(System.out);

 Then we call its format method


int num = 467;
formatter.format("%6d", num);

 This will output the value with the field width of 6.


THE format METHOD OF
Formatter
The general syntax is
format(<control string>, <expr1>, <expr2>, . . . )
 Example:
int num1 = 34, num2 = 9;
int num3 = num1 + num2;
formatter.format("%3d + %3d = %5d", num1, num2, num3);
THE format METHOD OF
PrintStream
Instead of using the Formatter class directly,
we can achieve the same result by using the
format method of PrintStream (System.out)
Formatter formatter = new Formatter(System.out);
formatter.format("%6d", 498);

is equivalent to

System.out.format("%6d", 498);
CONTROL STRINGS
 Integers
% <field width> d
 Real Numbers
% <field width> . <decimal places> f
 Strings
%s

 For other data types and more formatting


options, please consult the Java API for the
Formatter class.
ESTIMATING THE
EXECUTION

TIME
In many situations, we would like to know how
long it took to execute a piece of code. For
example,
− Execution time of a loop statement that finds
the greatest common divisor of two very large
numbers, or
− Execution time of a loop statement to display
all prime numbers between 1 and 100 million
 Execution time can be measured easily by using
the Date class.
USING THE Date CLASS
 Here's one way to measure the execution time.

Date startTime = new Date();

//code you want to measure the execution time

Date endTime = new Date();

long elapsedTimeInMilliSec =
endTime.getTime() – startTime.getTime();

You might also like