Java If-Else-If

Java If Statement is used to execute a block of code based on the result of a given condition.

Syntax

The syntax of if-else-if statement in Java is

if(condition1) {
    //statement(s)
} else if(condition2) {
    //statement(s)
} else if(condition3) {
    //statement(s)
} else {
    //statement(s)
}

If the condition1 evaluates to true, execute corresponding block of statements and the execution of if-else-if is completed. If the condition1 evaluates to false, check condtition2.

Now, If the condition2 evaluates to true, execute corresponding block of statements and the execution of if-else-if is completed. If the condition2 evaluates to false, check condtition3.

If the condition3 evaluates to true, execute corresponding block of statements and the execution of if-else-if completed. If the condition1 evaluates to false, execute else block.

Please note that there could be as many number of else if blocks as required.

else block at the end of if-else-if ladder is optional.

To put in simple terms, from top to bottom, the first condition that gets evaluated to true executes the corresponding block of statements.

Flow Diagram

The following flow diagram depicts the flow of program execution for an if-else-if statement based on conditions.

Examples

In the following example, we shall check if a number is divisible by 2, 3 or 5 using an if-else-if statement.

Java Program

public class Main {
    public static void main(String[] args) {
        int a = 15;

        if(a % 2 == 0) {
            System.out.println("a is divisible by 2.");
        } else if(a % 3 == 0) {
            System.out.println("a is divisible by 3.");
        } else if(a % 5 == 0) {
            System.out.println("a is divisible by 5.");
        } else {
            System.out.println("a is not divisible by 2, 3 or 4.");
        }
    }
}

a%2==0 is false. So, check the next condition. a%3==0 is true. Execute the corresponding block. If-else-if statement execution is completed.

Output

a is divisible by 3.

Conclusion

In this Java Tutorial, we learned how to write If-Else-If statement in Java, and how to use it in Java programs, with examples.