Java if-else Statement Example

The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if the condition is false.

Syntex

if(condition){  
     statement 1; //code if condition is true  
}else{  
     statement 2; //code if condition is false  
}  
Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is an expression that returns a boolean value.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.

Java if-else Statement Example

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
package net.javaguides.corejava.controlstatements.ifelse;

public class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}
Output:
Grade = C
Note that the value of test score can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

Java if-else-if Statement

A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.

Syntex

Syntax:

if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  

Java if-else-if Statement Example

Here is a program that uses an if-else-if ladder to determine which season a particular month is in.
package net.javaguides.corejava.controlstatements.ifelse;

public class IfElseIfStatementExample {
    public static void main(String args[]) {
        int month = 4; // April
        String season;
        if (month == 12 || month == 1 || month == 2)
            season = "Winter";
        else if (month == 3 || month == 4 || month == 5)
            season = "Spring";
        else if (month == 6 || month == 7 || month == 8)
            season = "Summer";
        else if (month == 9 || month == 10 || month == 11)
            season = "Autumn";
        else
            season = "Bogus Month";
        System.out.println("April is in the " + season + ".");
    }
}
Output:
April is in the Spring.

Reference

Comments