Java if-else-if Statement Example



Java if-else-if Statement Example demonstrates how to use if-else-if statement with an example in Java.

Java if-else-if Statement 

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

Syntax

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  
}  
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place.

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

https://www.javaguides.net/2018/10/java-if-ifelse-nestedif-ifelseif-statement-with-examples.html

Comments