Using The if-else Statement in Java

Java

The if-else statement is one of the selection statements in Java. We can use this statement to define and control the flow in our code.

In this tutorial, we’ll show you some examples of how to use if, if-else, if-else-if-else and nested if in Java.

What You’ll Need

Example 1: if Statement

This is the code snippet of if statement.

int score = 150;
if (score > 100) {
    System.out.println("The score is more than 100");
}

Output:

The score is more than 100

Note: We can define if statement without using else.

Example 2: if-else Statement

This is the code snippet of if-else statement.

int score = 30;
if (score >= 40) {
    System.out.println("The result is passed");
} else {
    System.out.println("The result is failed");
}

Output:

The result is failed

Example 3: if-else-if-else Statement

This is the code snippet of if-else-if-else statement.

String today = "Wednesday";
if (today.equals("Monday")) {
    System.out.println("Today is Monday");
} else if (today.equals("Tuesday")) {
    System.out.println("Today is Tuesday");
} else if (today.equals("Wednesday")) {
    System.out.println("Today is Wednesday");
} else if (today.equals("Thursday")) {
    System.out.println("Today is Thursday");
} else if (today.equals("Friday")) {
    System.out.println("Today is Friday");
} else {
    System.out.println("Today is weekend");
}

Output:

Today is Wednesday

Example 4: Nested if Statement

Nested if statement is a if statement is defined within another if statement.

This is the code snippet of nested if statement.

int score = 55;
if (score >= 40) {
    if (score < 60) {
        System.out.println("The result is grade C");
    }
} else {
    System.out.println("The result is failed");
}

Output:

The result is grade C

Summary

In this tutorial, we have shown you several examples of using if, if-else, if-else-if-else and nested if statements in Java.

You can get the example codes of this tutorial on GitHub.