Java If-Else Statements

The if and else statements in Java are control structures that allow you to execute code based on conditions. Let’s dive into their usage.

The if Statement

The if statement executes a block of code if its condition evaluates to true:

int number = 10;
    if (number > 5) {
        System.out.println("Number is greater than 5.");
    }

Adding else

The else statement runs a block of code if the condition is false:

int number = 3;
    if (number > 5) {
        System.out.println("Number is greater than 5.");
    } else {
        System.out.println("Number is 5 or less.");
    }

Using else if

To handle multiple conditions, use else if:

int number = 8;
    if (number > 10) {
        System.out.println("Number is greater than 10.");
    } else if (number > 5) {
        System.out.println("Number is greater than 5 but not greater than 10.");
    } else {
        System.out.println("Number is 5 or less.");
    }

Nested if Statements

You can nest if statements to check more complex conditions:

int x = 7, y = 12;
    if (x > 5) {
        if (y > 10) {
            System.out.println("x is greater than 5 and y is greater than 10.");
        }
    }

Output:

x is greater than 5 and y is greater than 10.

Next Steps

Practice writing programs with decision-making logic. Mastering if, else, and else if will enable you to build dynamic and interactive Java applications. Now you can learn about loops!