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

Lecture 3

This document covers key concepts in Object-Oriented Programming, focusing on abstraction, encapsulation, inheritance, and method overriding. It also discusses numerical data types, arithmetic operations, type casting, and the use of various classes like DecimalFormat and Math in Java. Additionally, it addresses visibility modifiers, local variables, and selection statements, providing a comprehensive overview of essential programming principles and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 3

This document covers key concepts in Object-Oriented Programming, focusing on abstraction, encapsulation, inheritance, and method overriding. It also discusses numerical data types, arithmetic operations, type casting, and the use of various classes like DecimalFormat and Math in Java. Additionally, it addresses visibility modifiers, local variables, and selection statements, providing a comprehensive overview of essential programming principles and practices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

Faculty of Information Technology

Fall 2020/21

Object-Oriented Programming
CS-201

Lec. (3)
Chapter 3

Numerical Data
Abstract
Abstraction is a way of describing complex problems
in simple terms, by ignoring some details.
Eliminating the nitty-gritty details let us focus on the bigger picture.
We can dig deeper once we have a broader understanding.
Encapsulation
The next fundamental idea to keep in mind when dealing with object-oriented
programming and classes is called "encapsulation".
We encapsulate something to protect it and keep its parts together.
Think of how medicine is enclosed in a shell called capsule.
In object-orientation,
this translates to packing together our properties and methods in a class.
Encapsulation also means hiding the gears and the levers.
What is Inheritance?
Generalization vs. Specialization

• Real-life objects are typically specialized versions of other more general


objects.
• The term “Student” describes a very general type of Students with known
characteristics.
• Post-Graduated Students and under-graduated students are Students
– They share the general characteristics of a Student.
– However, they have special characteristics of their own.
• Post Graduated have an interesting research area.
• Under Graduated have a Group no and class no .
• Post Graduated Students and under graduated students are specialized
versions of a student.

10-70
Overriding
By overriding a method of the superclass, we basically tell that we want a
different behavior in our subclass than the one we inherited.
Method overriding is straightforward:
we re-implement the method with the same name and parameters as the one
defined in the parent class and provide our own behavior.
Objectives
After you have read and studied this chapter, you should
be able to
• Select proper types for numerical data.
• Write arithmetic expressions in Java.
• Evaluate arithmetic expressions using the precedence rules.
• Describe how the memory allocation works for objects and primitive
data values.
• Write mathematical expressions, using methods in the Math class.
• Use the GregorianCalendar class in manipulating date information
such as year, month, and day.
• Use the DecimalFormat class to format numerical data
• Convert input string values to numerical data
• Perform input and output by using System.in and System.out
Data Type Precisions
The six data types differ in the precision of values they can store in
memory.
Arithmetic Operators
• The following table summarizes the arithmetic operators available in
Java.

This is an integer division


where the fractional part
is truncated.
Arithmetic Expression
• How does the expression
x + 3 * y
get evaluated? Answer: x is added to 3*y.
• We determine the order of evaluation by following the precedence
rules.
• A higher precedence operator is evaluated before the lower one. If
two operators are the same precedence, then they are evaluated left
to right for most operators.
Precedence Rules
Type Casting
• If x is a float and y is an int,
what will be the data type of the following expression?
x * y
The answer is float.
• The above expression is called a mixed expression.
• The data types of the operands in mixed expressions are converted based on the
promotion rules. The promotion rules ensure that the data type of the expression will
be the same as the data type of an operand whose type has the highest precision.
Explicit Type Casting
• Instead of relying on the promotion rules, we can make an explicit
type cast by prefixing the operand with the data type using the
following syntax:
( <data type> ) <expression>
• Example
Type case x to float and
(float) x / 3 then divide it by 3.

Type cast the result of the


(int) (x / y * 3.0) expression x / y * 3.0 to
int.
Implicit Type Casting
• Consider the following expression:
double x = 3 + 5;
• The result of 3 + 5 is of type int. However, since the
variable x is double, the value 8 (type int) is
promoted to 8.0 (type double) before being
assigned to x.
• Notice that it is a promotion. Demotion is not
allowed.

int x = 3.5; A higher precision value


cannot be assigned to a
lower precision variable.
Constants
• We can change the value of a variable. If we want the
value to remain the same, we use a constant.

final double PI = 3.14159;


final int MONTH_IN_YEAR = 12;
final short FARADAY_CONSTANT = 23060;

The reserved word These are constants,


These are called
final is used to also called named
literal constant.
declare constants. constant.
Primitive vs. Reference
• Numerical data are called primitive data types.
• Objects are called reference data types, because the contents are
addresses that refer to memory locations where the objects are
actually stored.
Primitive Data Declaration and Assignments

int firstNumber, secondNumber;


firstNumber = 234;
secondNumber = 87; A. Variables are
allocated in memory.

firstNumber 234
A
int firstNumber, secondNumber;
secondNumber 87
firstNumber = 234;
secondNumber = 87; B

B. Values are assigned


to variables.

Code State of Memory


Assigning Numerical Data

int number;
number = 237;
number = 35; number 35
237

A. The variable
is allocated in
int number; A memory.
number = 237; B B. The value 237
number = 35; C is assigned to
number.

C. The value 35
overwrites the
previous value 237.

Code State of Memory


Assigning Objects
customer
Customer customer;
customer = new Customer( );
customer = new Customer( );

Customer Customer
A

B A. The variable is
Customer customer;
allocated in memory.
customer = new Customer( );
B. The reference to the
customer = new Customer( ); new object is assigned
to customer.

C C. The reference to
another object overwrites
the reference in customer.

Code State of Memory


Having Two References to a Single Object

Customer clemens, twain; clemens


clemens = new Customer( );
twain = clemens; twain

A Customer

Customer clemens, twain;


twain, B A. Variables are
allocated in memory.
clemens = new Customer( );
B. The reference to the
twain = clemens; new object is assigned
to clemens.

C C. The reference in
clemens is assigned to
customer.

Code State of Memory


Type Mismatch
• Suppose we want to input an age. Will this work?

int age;

age = JOptionPane.showInputDialog(
null, “Enter your age”);

• No.
String value cannot be assigned directly to an
int variable.
Type Conversion
• Wrapper classes are used to perform necessary type
conversions, such as converting a String object to a
numerical value.

int age;
String inputStr;

inputStr = JOptionPane.showInputDialog(
null, “Enter your age”);

age = Integer.parseInt(inputStr);
Other Conversion Methods
Common Scanner Methods:
Method Example

nextByte( ) byte b = scanner.nextByte( );


nextDouble( ) double d = scanner.nextDouble( );
nextFloat( ) float f = scanner.nextFloat( );
nextInt( ) int i = scanner.nextInt( );
nextLong( ) long l = scanner.nextLong( );
nextShort( ) short s = scanner.nextShort( );
next() String str = scanner.next();
The DecimalFormat Class
• Use a DecimalFormat object to format the numerical output.

double num = 123.45789345;

DecimalFormat df = new DecimalFormat(“0.000”);


//three decimal places

System.out.print(num); 123.45789345

System.out.print(df.format(num));
123.458
The Math class
• The Math class in the java.lang package contains class
methods for commonly used mathematical functions.

double num, x, y;

x = …;
y = …;

num = Math.sqrt(Math.max(x, y) + 12.4);


Computing the Height of a Pole

alphaRad = Math.toRadians(alpha);
betaRad = Math.toRadians(beta);

height = ( distance * Math.sin(alphaRad) * Math.sin(betaRad) )


/
Math.sqrt( Math.sin(alphaRad + betaRad) *
Math.sin(alphaRad - betaRad) );
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
arguments and the
Demo demo = new Demo( );
parameters must be the
int i = 5; int k = 14; 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 assignment-
. . .
}
3 parameters compatible (e.g. you
}
cannot pass a double
argument to a int
Receiving Side parameter)
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
Passing a Student Object 1
LibraryCard card2; student st
card2 = new LibraryCard();
card2.setOwner(student);
card2

Passing Side 1

class LibraryCard { 2
private Student owner;
public void setOwner(Student st) {
owner = st; 2 : LibraryCard : Student
}
}
owner name
Receiving Side “Jon Java”

borrowCnt email
1 Argument is passed 0 “[email protected]

2 Value is assigned to the


data member State of Memory
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 the owner
of two LibraryCard objects
pointing to the same Student
object
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.
Accessibility Example
… class Service {
public int memberOne;
Service obj = new Service();
private int memberTwo;

obj.memberOne = 10; public void doOne() {



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

Client Service
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.
Access Modifiers
▪ There are 4 types of java access specifiers:
✔ default
✔ private
✔ protected
✔ public
Modifier Access Level

Class Package Subclass Everywhere


default Y Y N N
private Y N N N
protected Y Y Y N
public Y Y Y Y
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.
Diagram Notation for Visibility

public – plus symbol (+)


private – minus symbol (-)
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;
}
Local, Parameter & 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.
Local, Parameter & Data Member
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
Chapter 5

Selection Statements
Objectives
After you have read and studied this chapter, you should be able to

• Implement a selection control using if statements


• Implement a selection control using switch statements
• Write boolean expressions using relational and boolean expressions
• Evaluate given boolean expressions correctly
• Nest an if statement inside another if statement
• Describe how objects are compared
• Choose the appropriate selection control statement for a given task
The if Statement
int testScore;

testScore = //get test score input

if (testScore < 70)


This statement is
JOptionPane.showMessageDialog(null, executed if the testScore
is less than 70.
"You did not pass" );

else
This statement is
JOptionPane.showMessageDialog(null, executed if the testScore
"You did pass" ); is 70 or higher.
Syntax for the ifif (Statement
<boolean expression> )

<then block>
else

<else block> Boolean Expression

if ( testScore < 70 )

Then Block JOptionPane.showMessageDialog(null,


"You did not pass" );

else

Else Block JOptionPane.showMessageDialog(null,


"You did pass " );
Control Flow
false true
testScore <
70 ?

JOptionPane. JOptionPane.
showMessageDialog showMessageDialog
(null, "You did pass"); (null, "You did not 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)


{
JOptionPane.showMessageDialog(null,
"You did not pass“ );
Then Block
JOptionPane.showMessageDialog(null,
“Try harder next time“ );
}
else
{
JOptionPane.showMessageDialog(null,
“You did pass“ );
Else Block
JOptionPane.showMessageDialog(null,
“Keep up the good work“ );
}
Style Guide if ( <boolean expression> ) {

}
else {
Style 1

}

if ( <boolean expression> )
{

} Style 2
else
{

}
The if-then Statement
if ( <boolean expression> )

<then block>

Boolean Expression

if ( testScore >= 95 )

Then Block JOptionPane.showMessageDialog(null,


"You are an honor student");
Control Flow of if-then
true
testScore >=
95?

JOptionPane.
showMessageDialog (null,
false "You are an honor 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
inner if
false true
testScore >=
70 ?

messageBox.show false studentAge < true


("You did not 10 ?
pass");

messageBox.show
messageBox.show
("You did a great
("You did pass");
job");
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 statement
else
if (num3 < 0) negativeCount++;
negativeCount = 1;
else increments the variable by one
negativeCount = 0;
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
Are and
else
different?
A B

if (x < y) A Both A and 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 }
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 && Q P || Q !P
false false false false true
false true false true true
true false false true false
true true true true false
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");
}

They are not equal Not equal because 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");
}

They are equal It's equal here 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");
}

They are equal It's equal here because


str1 and str2 have the
same sequence of
characters.
The Semantics of ==
In Creating String Objects
Chapter 6

Repetition Statements
Objectives
After you have read and studied this chapter, you should be able to
• Implement repetition control in a program using while statements.
• Implement repetition control in a program using do-while statements.
• Implement a generic loop-and-a-half repetition control statement
• Implement repetition control in a program using for statements.
• Nest a loop repetition statement inside another repetition statement.
• Choose the appropriate repetition control statement for a given task
• Prompt the user for a yes-no reply using the showConfirmDialog method of
JOptionPane.
• (Optional) Write simple recursive methods
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 statements are


executed as long as
number is less than or
number = number + 1; equal to 100.

}
Syntax for the while Statement
while ( <boolean expression> )

<statement>

Boolean Expression

while ( number <= 100 ) {

sum = sum + number;


Statement
(loop body)
number = number + 1;
}
Control Flow of while

int sum = 0, number = 1

true
number <=
100 ?

false
sum = sum + number;

number = number + 1;
More Examples
1 int sum = 0, number = 1; Keeps adding the
numbers 1, 2, 3, … until
while ( sum <= 1000000 ) { the sum becomes larger
than 1,000,000.
sum = sum + number;
number = number + 1;
}

2
int product = 1, number = 1,
count = 20, lastNumber; Computes the product of
the first 20 odd integers.
lastNumber = 2 * count - 1;

while (number <= lastNumber) {


product = product * number;
number = number + 2;
}
Finding GCD

Direct Approach More Efficient Approach


Example: Testing Input Data
String inputStr;
Priming Read
int age;

inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);

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


JOptionPane.showMessageDialog(null,
"An invalid age was entered. Please try again.");

inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");

age = Integer.parseInt(inputStr);
}
Useful Shorthand Operators
sum = sum + number; is equivalent to sum += 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
1 int product = 0;

while ( product < 500000 ) {


product = product * 5;
}

Infinite Loops
Both loops will not
terminate because the
boolean expressions will
2 int count = 1; never 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
1 float count = 0.0f;

while ( count != 1.0f ) {


count = count + 0.3333333f;
} //seven 3s
Using Real Numbers
Loop 2 terminates, but Loop
1 does not because only an
approximation of a real
number can be stored in a
2 float count = 0.0f; computer memory.

while ( count != 1.0f ) {


count = count + 0.33333333f;
} //eight 3s

Avoid using real numbers for counter variables as much as possible. If you use
them, then be aware of the pitfall and ensure that the loop terminates.
Loop Pitfall – 2a
1 int result = 0; double cnt = 1.0;
while (cnt <= 10.0){
cnt += 1.0;
result++;
}
System.out.println(result);
10 Using Real Numbers
Loop 1 prints out 10, as
expected, but Loop 2 prints
out 11. The value 0.1 cannot
be stored precisely in
2 int result = 0; double cnt = 0.0; computer memory.
while (cnt <= 1.0){
cnt += 0.1;
result++;
}
System.out.println(result);
11
Avoid using real numbers for counter variables as much as possible. If you use
them, then be aware of the pitfall and ensure that the loop terminates.
Loop Pitfall - 3
• Goal: Execute the loop body 10 times.
1 count = 1; 2 count = 1;
while ( count < 10 ){ while ( count <= 10 ){
. . . . . .
count++; count++;
} }

3 count = 0; 4 count = 0;
while ( count <= 10 ){ while ( count < 10 ){
. . . . . .
count++; count++;
} }

1 and 3 exhibit off-by-one error.


The do-while Statement
int sum = 0, number = 1;

do {

These statements are


sum += number; executed as long as sum
is less than or equal to
number++; 1,000,000.

} while ( sum <= 1000000 );


Syntax for the do-while
do
Statement
<statement>

while ( <boolean expression> ) ;

do {

sum += number; Statement


number++; (loop body)

} while ( sum <= 1000000 );

Boolean Expression
Control Flow of do-while
int sum = 0, number = 1

sum += number;

number++;

true
sum <=
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;

while (true){

name = JOptionPane.showInputDialog(null, "Your name");

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

JOptionPane.showMessageDialog(null, "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.
Confirmation Dialog
• A confirmation dialog can be used to prompt the user to
determine whether to continue a repetition or not.

JOptionPane.showConfirmDialog(null,
/*prompt*/ "Play Another Game?",
/*dialog title*/ "Confirmation",
/*button options*/ JOptionPane.YES_NO_OPTION);
Example: Confirmation Dialog
boolean keepPlaying = true;
int selection;

while (keepPlaying){

//code to play one game comes here


// . . .

selection = JOptionPane.showConfirmDialog(null,
"Play Another Game?",
"Confirmation",
JOptionPane.YES_NO_OPTION);

keepPlaying = (selection == JOptionPane.YES_OPTION);


}
The for Statement
int i, sum = 0, number;

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

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

}
These statements are
executed for 20 times
( i = 0, 1, 2, … , 19).
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )

<statement>

Boolean
Initialization Increment
Expression

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

number = scanner.nextInt(); Statement


sum += number; (loop body)
}
Control Flow of for

i = 0;

i < 20 ?
false
true

number = . . . ;
sum += number;

i ++;
More for Loop Examples
1 for (int i = 0; i < 100; i += 5)

i = 0, 5, 10, … , 95

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

j = 2, 4, 8, 16, 32

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

k = 100, 99, 98, 97, ..., 1


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.


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();
What will be the output of the program?

Answer: 15 15
What will be the output of the program?

Answer: false true


What will be the output of the program?

Answer: sst s st
With x = 0, which of the following are legal lines of Java code for changing the
value of x to 1?

1. x++;
2. x = x + 1;
3. x += 1;
4. x =+ 1;

Answer: 1, 2, 3, & 4
What will be the output of the program?

Answer: 1.5 1
What will be the output of the program?

Answer:
Enter your marks
85
You pass the exam
What will be the output of the program?

Answer: t
What will be the output of the program?

Answer: 48
What will be the output of the program?

Answer: FALSE
What will be the output of the program?

Answer: FALSE
What will be the output of the program?

Answer: 12
What will be the output of the program?

Answer: 27 9
What will be the output of the program?

Answer: Compilation error


What will be the output of the program?

Answer: 40
What will be the output of the program?

Answer: iiiii
What will be the output of the program?

Answer: 15
What will be the output of the program?

Answer: x=15, no output


What will be the output of the program?

Answer: Compilation fails


What will be the output of the program?

Answer: Compilation fails


What will be the output of the program?

Answer: 2
What will be the output of the program?

Answer: 6
What will be the output of the program?

Answer: i = 5 and j = 6

You might also like