0% found this document useful (0 votes)
5 views17 pages

Lecture Notes 3 Chapter 4 and 5

The document provides lecture notes on control structures in Java, detailing three types: sequence, selection, and repetition statements. It explains various selection statements like if, if...else, and switch, as well as repetition statements including while, do...while, and for loops. Additionally, it covers logical operators, operator precedence, and the potential pitfalls such as the dangling-else problem and infinite loops.
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)
5 views17 pages

Lecture Notes 3 Chapter 4 and 5

The document provides lecture notes on control structures in Java, detailing three types: sequence, selection, and repetition statements. It explains various selection statements like if, if...else, and switch, as well as repetition statements including while, do...while, and for loops. Additionally, it covers logical operators, operator precedence, and the potential pitfalls such as the dangling-else problem and infinite loops.
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

Object Oriented Programming (1902110) Second Semester 2025/2026

Lecture notes 3

Summarized by:

Mrs. Aseel Al-Anani - Mrs. Rola Al-Khalid - Dr. Rana Yousef - Dr. Esra Alzaghoul

21
Chapters 4 and 5: Control Structures
• Java has three kinds of control structures:

– Sequence statement

– Selection statements (three types)

– Repetition statements (three types)

• Sequential statements

– Statements are normally executed one after the other in the order in which they are
written.

• Selection Statements

– Java has three types of selection statements:

– if statement

• Single-selection statement

– if…else statement

• Double-selection statement

– switch statement

• Multiple-selection statement

• if statement

– Execute an action if the specified condition is true

– For example, the statement:

if ( studentGrade >= 60 )

[Link]( "Passed" );

If the condition is true, “Passed” is printed, and the next statement in order is performed.
If the condition is false, the Print statement is ignored, and the next statement in order is
performed. The indentation of the second line of this selection statement is optional, but
recommended.

22
• if…else statement

– Executes one action if the specified condition is true or a different action if the specified
condition is false

– For example, the statement:

if ( grade >= 60 )

[Link]( "Passed" );

else

[Link]( "Failed" );

prints “Passed” if the student’s grade is greater than or equal to 60, but prints “Failed” if
it is less than 60. In either case, after printing occurs, the next statement in sequence is
performed.

• Conditional Operator ( ? : )

– Java provides the conditional operator (?:) that can be used in place of an if…else
statement.

– ?: is a ternary operator (takes three operands)

– ? : and its three operands form a conditional expression

• The first operand (to the left of the ?) is a boolean expression.

• The second operand (between the ? and :) is the value of the conditional
expression if the boolean expression is true

• The third operand (to the right of the :) is the value of the conditional expression
if the boolean expression evaluates to false.

– For example,

[Link]( studentGrade >= 60 ? "Passed" : "Failed" );

The conditional expression in this statement evaluates to the string "Passed" if the
boolean expression studentGrade >= 60 is true and evaluates to the string "Failed" if the
boolean expression is false.

23
• Nested if…else statements

– if…else statements can be put inside other if…else statements

– For example, the following java code represents a nested if…else that prints A for exam
grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the
range 70 to 79, D for grades in the range 60 to 69 and F for all other grades:

if ( studentGrade >= 90 )
[Link]( "A" );
else
if ( studentGrade >= 80 )
[Link]( "B" );
else
if ( studentGrade >= 70 )
[Link]( "C" );
else
if ( studentGrade >= 60 )
[Link]( "D" );
else
[Link]( "F" );
- Most Java programmers prefer to write the preceding if…else statement as

if ( studentGrade >= 90 )
[Link]( "A" );
else if ( studentGrade >= 80 )
[Link]( "B" );
else if ( studentGrade >= 70 )
[Link]( "C" );
else if ( studentGrade >= 60 )
[Link]( "D" );
else
[Link]( "F" );
The two forms are identical except for the spacing and indentation, which the compiler
ignores.

24
• Dangling-else problem

– The Java compiler always associates an else with the immediately preceding if unless told
to do otherwise by the placement of braces ({ and }). This behavior can lead to what is
referred to as the dangling-else problem. For example:

if ( x > 5 )
if ( y > 5 )
[Link]( "x and y are > 5" );
else
[Link]( "x is <= 5" );
appears to indicate that if x is greater than 5, the nested if statement determines whether
y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears
that if x is not greater than 5, the else part of the if…else outputs the string "x is <= 5".

Beware! This nested if…else statement does not execute as it appears. The compiler
actually interprets the statement as:

if ( x > 5 )
if ( y > 5 )
[Link]( "x and y are > 5" );
else
[Link]( "x is <= 5" );
To force the nested if…else statement to execute as it was originally intended, we must
write it as follows:

if ( x > 5 )
{
if ( y > 5 )
[Link]( "x and y are > 5" );
}
else
[Link]( "x is <= 5" );
The braces ({}) indicate to the compiler that the second if statement is in the body of the

first if and that the else is associated with the first if.

25
• Blocks

– Braces { } associate statements into blocks

– To include several statements in the body of an if , enclose the statements in braces ({


and }).

– The following example includes a block in the else-part of an if…else statement:

if ( grade >= 60 )

[Link]( "Passed" );

else

[Link]( "Failed" );

[Link]("You must take this course again");

In this case, if grade is less than 60, the program executes both statements in the body of
the else and prints

Failed

You must take this course again

• Logical operators

- Allows for forming more complex conditions (Combines simple conditions)

- Some Java logical operators are:

o && (conditional AND)

o || (conditional OR)

o & (boolean logical AND)

o | (boolean logical inclusive OR)

o ! (logical NOT)

26
• Conditional AND (&&) Operator

expression1 expression2 expression1 && expression2


false false False
false true False
true false False
true true True

– Consider the following if statement

if ( gender == “FEMALE” && age >= 65 )


++count;
• Conditional OR (||) Operator

expression1 expression2 expression1 || expression2


false false false
false true true
true false true
true true true

– Consider the following if statement

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )


[Link]( “Student grade is A” );
• Short-Circuit Evaluation of Complex Conditions

– Parts of an expression containing && or || operators are evaluated only until it is known
whether the condition is true or false

– E.g., ( gender == “FEMALE” ) && ( age >= 65 )

• Stops immediately if gender is not equal to FEMALE

• Boolean Logical AND (&) Operator

– Works identically to && BUT & always evaluates both operands

• Boolean Logical OR (|) Operator

– Works identically to || BUT | always evaluate both operands

• Logical Negation (!) Operator

– Unary operator

27
• The precedence of the Java operators. The operators are shown from top to bottom in decreasing
order of precedence.

Operators Associativity Type


++ -- Left to right Increment and decrement operators
* / % Left to right Multiplicative
+ - Left to right Additive
< <= > >= Left to right Relational
== != Left to right Equality
& Left to right Boolean logical AND
| Left to right Boolean logical inclusive OR
&& Left to right Conditional AND
|| Left to right Conditional OR
?: Right to left Conditional
= += -= *= /= %= Right to left Assignment

- switch statement

- Used for multiple selections

- The switch statement performs one of many different actions depending on the value of an
expression.

- The general format of the switch statement is:

switch(Expression){
case value1:
Statement;
break;
case value1:
Statement;
break;
.
.
default:
Statement;
}

28
- Although each case and the default case in a switch can occur in any order, place the default
case last. When the default case is listed last, the break for that case is not required. Some
programmers include this break for clarity and symmetry with other cases
- Expression in each case can be:

– Constant integral expression

• Combination of integer constants that evaluates to a constant integer value (byte,


short, int or char, but not long)

– Character constant

• E.g., ‘A’, ‘7’ or ‘$’

– Constant variable

• Declared with keyword final

– String

- The switch statement differs from other control statements in that it does not require braces
around multiple statements in a case.

- Without break statements, each time a match occurs in the switch, the statements for that
case and subsequent cases execute until a break statement or the end of the switch is
encountered.

- If no match occurs between the controlling expression’s value and a case label, the default
case executes. If no match occurs and the switch does not contain a default case, program
control simply continues with the first statement after the switch.

- Example:
int i=1;
switch (i) {
case 0:
[Link]("zero");
break;
case 1:
[Link]("one");
case 2:
[Link]("two");
default:
[Link]("default");
}
The Output is:
one
two
default
29
• Repetition statements ( looping statements)
– Repeatedly performs an action while its loop-continuation condition remains true
– Java provides three repetition statements:
• while statement
• Performs the actions in its body zero or more times
• do…while statement
• Performs the actions in its body one or more times
• for statement
• Performs the actions in its body zero or more times
• while statement
– Repeats an action while its loop-continuation condition remains true
– The general form of while statement is:
initialization;
while ( loopContinuationCondition ) {
statement;
increment;}
}
– Not providing, in the body of a while statement, an action that eventually causes the
condition in the while to become false normally results in a logic error called an infinite
loop, in which the loop never terminates
– Counter-controlled repetition requires:
• Control variable (loop counter)
• Initial value of the control variable
• Increment/decrement of control variable through each loop
• Loop-continuation condition that tests for the final value of the control variable
– Example 1:
1 // Fig. 5.1: [Link]
2 // Counter-controlled repetition with the while repetition statement.
3
4 public class WhileCounter
5 {
6 public static void main( String args[] )
7 {
8 int counter = 1; // declare and initialize control variable
9
10 while ( counter <= 10 ) // loop-continuation condition
11 {
12 [Link]( "%d ", counter );
13 ++counter; // increment control variable by 1
14 } // end while
15
16 [Link](); // output a newline
17 } // end main
18 } // end class WhileCounter

1 2 3 4 5 6 7 8 9 10

30
- Note that the program performs the body of this while even when the control variable is
10. The loop terminates when the control variable exceeds 10 (i.e., counter becomes 11)

- The program in Fig. 5.1 can be made more concise by initializing counter to 0 in line 8 and
preincrementing counter in the while condition as follows:

while ( ++counter <= 10 ) // loop-continuation condition

[Link]( "%d ", counter );

- This code saves a statement (and eliminates the need for braces around the loop’s body),
because the while condition performs the increment before testing the condition.

- Example 2:

31
The output:

Example 3: int x = 0,y=0;


while (x <= 0) {
if (x < 0){
y = x;
x =x+4;
} Output: y= -3
else{
y = -x;
x = x-3;
}
}
[Link]("y=%d",y);

• do…while Repetition Statement


– Similar to while structure, but The do…while statement tests the loop-continuation condition
after executing the loop’s body; therefore, the body always executes at least once.

– The general format of the do/while statement is:

do{
statements
} while ( condition );

32
Example2:

int x=1;
do{
The output is:
x = x*2;
[Link](" " +x);
2 4 8 16
} while(x<=8);

• for Repetition Statement


- Java provides the for repetition statement, which specifies the counter-controlled-
repetition details in a single line of code.
- The general format of the for statement is:
for (initialization ; loopContinuationCondition ; increment )
statement;
where :
- the initialization expression names the loop’s control variable and optionally provides
its initial value, loopContinuationCondition is the condition that determines whether
the loop should continue executing and increment modifies the control variable’s
value (possibly an increment or decrement), so that the loop-continuation condition
eventually becomes false.
- The two semicolons in the for header are required
- The for statement can be represented with an equivalent while statement as follows:
initialization;
while ( loopContinuationCondition ) {
statement;
increment; }
Example:
1 // Fig. 5.2: [Link]
2 // Counter-controlled repetition with the for repetition statement.
3
4 public class ForCounter
5 {
6 public static void main( String args[] )
7 {
8 // for statement header includes initialization,
9 // loop-continuation condition and increment
10 for ( int counter = 1; counter <= 10; counter++ )
11 [Link]( "%d ", counter );
12
13 [Link](); // output a newline
14 } // end main
15 } // end class ForCounter
- Note: When a for statement’s control variable is declared in the initialization section of the for’s
1 2 3 4 5 6 7 8 9 10
header, using the control variable after the for’s body is a compilation error.

33
- Placing a semicolon immediately to the right of the right parenthesis of a for header makes that
for’s body an empty statement. This is normally a logic error.

- Infinite loops occur when the loop-continuation condition in a repetition statement never
becomes false. To prevent this situation in a counter-controlled loop, ensure that the control
variable is incremented (or decremented) during each iteration of the loop. In a sentinel-
controlled loop, ensure that the sentinel value is eventually input.

Examples Using the for Statement


• Varying control variable in for statement
– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in decrements of –1
• for ( int i = 100; i >= 1; i-- )
– Vary control variable from 7 to 77 in increments of 7
• for ( int i = 7; i <= 77; i += 7 )
– Vary control variable from 20 to 2 in decrements of 2
• for ( int i = 20; i >= 2; i -= 2 )
– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20
• for ( int i = 2; i <= 20; i += 3 )
– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
• for ( int i = 99; i >= 0; i -= 11 )
– Example: Summing the Even Integers from 2 to 20

34
- All three expressions in a for header are optional. If the loopContinuationCondition is omitted,
Java assumes that the loop-continuation condition is always true, thus creating an infinite loop.

- You might omit the initialization expression if the program initializes the control variable before
the loop. You might omit the increment expression if the program calculates the increment with
statements in the loop’s body or if no increment is needed.

- The initialization, loop-continuation condition and increment portions of a for statement can
contain arithmetic expressions. For example, assume that x = 2 and y = 10. If x and y are not
modified in the body of the loop, the statement

for ( int j = x; j <= 4 * x * y; j += y / x )

is equivalent to the statement

for ( int j = 2; j <= 80; j += 5 )

- If the loop-continuation condition is initially false, the program does not execute the for
statement’s body.

- Example:
int a =0;
int b = 4;
for (a =1; a<b;a++)
[Link](a++);
The output is:
1
3

• Nested Loops:

- The body of a loop can contain itself a loop, called a nested loop. It is possible to nest an
arbitrary number of loops. If a loop is nested the inner loop will execute all of its iterations for
each time the outer loop executes once.
- Example:

for (int i =1 ; i<=3;i++){


for (int j =4; j<=5; j++)
[Link](i+" "+j+" " );
[Link]();
}

The output is:


1 4 1 5
2 4 2 5
3 4 3 5

35
break/continue statements: for changing the flow of control

1. break statement

– Causes immediate exit from control structure


– Used in while, for, do…while or switch statements

36
continue statement

– Skips remaining statements in loop body


– Proceeds to next iteration
– Used in while, for or do…while statements

1 // Fig. 5.13: [Link]


2 // continue statement terminating an iteration of a for statement.
3 public class ContinueTest
4 {
5 public static void main( String args[] )
6 {
7 for ( int count = 1; count <= 10; count++ ) // loop 10 times
8 {
9 if ( count == 5 ) // if count is 5,
10 continue; // skip remaining code in loop
11
12 [Link]( "%d ", count );
13 } // end for
14
15 [Link]( "\nUsed continue to skip printing 5" );
16 } // end main
17 } // end class ContinueTest

1 2 3 4 6 7 8 9 10
Used continue to skip printing 5

37

You might also like