2. 3 Types Flow of Control
ï‚ž Sequential (we had learn in previous topic)
ï‚— The statements in a program are executed
in sequential order
ï‚ž Selection
ï‚— allow the program to select one of multiple
paths of execution.
ï‚— The path is selected based on some
conditional criteria (boolean expression)
ï‚ž Repetition (we will learn in next topic)
3. Flow of Control: Sequential
Structures
statement1
statement2
statement3
4. Flow of Control: Selection
Structures
ï‚ž If the boolean expression evaluates to true, the
statement will be executed. Otherwise, it will be
skipped.
5. Flow of Control: Selection
Structures
ï‚ž There are 3 types of Java selection
structures:
ï‚— if statement
ï‚— if-else statement
ï‚— switch statement
6. The if Statement
ï‚ž The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
7. Logic of an if statement
condition
evaluated
statement
true
false
9. Boolean Expressions
ï‚ž A condition often uses one of Java's
equality operators or relational
operators, which all return boolean
results:
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
10. The if Statement
if (total > MAX)
charge = total * MAX_RATE;
System.out.println ("The charge is " + charge);
ï‚ž First the condition is evaluated -- the value of total
is either greater than the value of MAX
ï‚ž If the condition is true, the assignment statement is
executed -- if it isn’t, it is skipped.
ï‚ž Either way, the call to println is executed next
11. Java code example
class Count
{
public static void main (String args[])
{
double y=15.0;
double x=25.0;
if (y!=x)
System.out.println("Result : y not equal
x");
}
}
13. Block Statements
ï‚ž Several statements can be grouped together into a
block statement delimited by braces
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
14. Block Statements
if (amount <= balance)
{
balance = balance - amount;
System.out.println(“Acct new balance = “ +
balance);
}
COMPARE WITH
if (amount <= balance)
balance = balance - amount;
System.out.println(“Acct new balance = “ + balance);