Java Code Example: nested if-else statement

When an if-else statement is executed in the body of another if-else statement, it is called nested.

Code Explanation

LineDescription
3Initializes the variable number with the value 56
5If the value of number is less than or equal to 100
6 – 7If the value of number is less than 50, print the string “Value is smaller than 50”
8 – 9If the value of number is less than 50, print the string “Value is 50”
10 – 11Otherwise the string Value is between 51 und 100 is output
13 – 14If the value of number is greater than 100 the following string “Value is greater than 100” is output
public class NestedIfElseStatement {
    public static void main(String[] args) {
        int number = 56;
    
        if (number <= 100) {
            if (number < 50) {
                System.out.print("Value is smaller than 50");
            } else if (number == 50) {
                System.out.print("Value is 50");
            } else {
                System.out.print("Value is between 51 und 100");
            }
        } else {
            System.out.print("Value is greater than 100");
        }
    }
}
Output
Value is between 51 und 100