J.E.D.I
6.2.3 if-else-if statement
The statement in the else-clause of an if-else block can be another if-else structures. This cascading of structures allows us to make more complex selections.
The if-else if statement has the form, if boolean_expression1
statement1; else if boolean_expression2
statement2; else
statement3; Take note that you can have many else-if blocks after an if-statement. The else-block is
optional and can be omitted. In the example shown above, if boolean_expression1 is true, then the program executes statement1 and skips the other statements. If
boolean_expression2 is true, then the program executes statement 2 and skips to the statements following statement3.
Introduction to Programming I 99
Figure 6.3: Flowchart of If-Else-If Statement
J.E.D.I
For example, given the code snippet, int grade = 68;
if grade 90 { System.out.printlnVery good;
} else if grade 60 {
System.out.printlnVery good; }
else{ System.out.printlnSorry you failed;
}
6.2.4 Common Errors when using the if-else statements:
1. The condition inside the if-statement does not evaluate to a boolean value. For example,
WRONG int number = 0;
if number { some statements here
} The variable number does not hold a Boolean value.
2. Using = instead of == for comparison. For example, WRONG
int number = 0; if number = 0 {
some statements here }
This should be written as, CORRECT
int number = 0; if number == 0 {
some statements here }
3. Writing elseif instead of else if.
Introduction to Programming I 100
J.E.D.I
6.2.5 Example for if-else-else if
public class Grade {
public static void main String[] args {
double grade = 92.0;
if grade = 90 { System.out.println Excellent ;
} else if grade 90 grade = 80{
System.out.printlnGood job ; }
else if grade 80 grade = 60{ System.out.printlnStudy harder ;
} else{
System.out.printlnSorry, you failed.; }
} }
Introduction to Programming I 101
J.E.D.I
6.2.6 switch statement