Java If-Else

Java If-Else statement is used to execute on of the two code blocks based on a given condition.

In this tutorial, we will learn the syntax and examples for If-Else statement.

Syntax

The syntax of If-Else statement is

if(condition) {
    //if code block
} else {
    //else code block
}

If the condition evaluates to true, if code block is executed.

If the condition evaluates to false, else code block is executed.

Flow Diagram

The following flow diagram depicts the execution flow of an if-else statement in Java.

Java If-Else

Examples

In the following example, we are checking the condition that if x is even. We also have an else block accompanying if block.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = -2;
        if(x > 0){
            System.out.println("x is positive.");
        } else {
            System.out.println("x is not positive.");
        }
    }
}

Output

x is not positive.

In the following example, we will check if given number is even or odd, and print a message to console, using if-else statement.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = 6;
        if(x % 2 == 0){
            System.out.println("x is even.");
        } else {
            System.out.println("x is odd.");
        }
    }
}

Output

x is even.

Nested If-Else Statement

Since If-Else is just another statement in Java, we can write an If-Else statement inside another If-Else statement. Since an If-Else statement is nested in another If-Else, we may call this as Nested If-Else statement.

In the following example, we have written a Nested If-Else statement.

Main.java

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

        if(a % 2 == 1) {
            System.out.println("a is odd number.");
            if(a<10) {
                System.out.println("a is less than 10.");
            } else {
                System.out.println("a is not less than 10.");
            }
        } else {
            System.out.println("a is even number.");
        }
    }
}

Run the program and you will get the following output in console.

Output

a is odd number.
a is less than 10.

Conclusion

In this Java Tutorial, we learned how to write an If-Else statement, nested if-else statement, and presented some Java examples.