Types of Java Statements: If If-Else Switch
Types of Java Statements: If If-Else Switch
• Conditional/Selection Statements
• if
• if-else
• Switch
• Iteration Statements
• for
• while
• do-while
Conditional Statements
• A conditional statement lets us choose which
statement will be executed next by using a
conditional test
4
Block Statements
• Several statements can be grouped together into a block
statement
• A block is delimited by braces : { … }
• A block statement can be used wherever a statement is
called for by the Java syntax
• if (guess == answer) {
System.out.println(“You guessed correct!”);
correct++;
} else {
System.out.println(“You guessed wrong.”);
wrong++;
}
5
Nested if Statements
• The statement executed as a result of an if
statement or else clause could be another if
statement
6
Multiway Selection: else if
• Sometime you want to select one option from
several alternatives
if (conditon1) conditon1
true
statement1
evaluated
statement1; false
else if (condition2) conditon2 true
statement2
statement2; evaluated
false
else if (condition3) true
conditon3 statement3
statement3; evaluated
else false
statement4
statement4;
else if example
double numberGrade = 83.6;
char letterGrade;
if (numberGrade >= 89.5) {
Output:
letterGrade = ‘A’;
} else if (numberGrade >= 79.5) { My Grade is 83.6, B
letterGrade = ‘B’;
} else if (numberGrade >= 69.5) {
letterGrade = ‘C’;
} else if (numberGrade >= 59.5) {
letterGrade = ‘D’;
} else {
letterGrade = ‘F’;
}
System.out.println(“My Grade is ” + numberGrade + “, ” + letterGrade);
The switch Statement
• The switch statement provides another means to
decide which statement to execute next
initialization
condition
evaluated
true false
statement
increment
for Example
final int LIMIT = 5;
for (int count = 1; count <= LIMIT; count++) {
System.out.println(count);
}
Output:
1
2
3
4
5
The for Statement
• Each expression in the header of a for loop is
optional
• If the initialization is left out, no initialization is
performed
• If the condition is left out, it is always
operation is performed
• Both semi-colons are always required in the for
loop header
The while Statement
• The while statement has the following syntax:
while is a while (condition)
reserved word statement;
20
Logic of a while Loop
condition
evaluated
true false
statement
23
The do Statement
• The do statement has the following syntax:
do and do{
while are statement;
reserved } while (condition);
words
statement
condition
evaluated
true
true false condition
evaluated
statement
false
Nested Loops
• Similar to nested if statements, loops can be
nested as well