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);