Java Code Example: nested if-else statement

The NestedIfElseStatement Java program demonstrates the use of nested if-else statements to conditionally execute code based on multiple conditions.

In the program, there is an integer variable number that is initialized to 56. The nested if-else statements check the value of number and execute the appropriate code block based on the following conditions:

  • If number is less than or equal to 100, the code block inside the outer if statement is executed, which contains additional if-else statements to further check the value of number.
    • If number is less than 50, the code block inside the first if statement is executed, which prints a message indicating that number is smaller than 50.
    • If number is equal to 50, the code block inside the else if statement is executed, which prints a message indicating that number is 50.
    • If number is greater than 50 but less than or equal to 100, the code block inside the second else statement is executed, which prints a message indicating that number is between 51 and 100.
  • If number is greater than 100, the code block inside the else statement is executed, which prints a message indicating that number is greater than 100.

In this case, number is between 51 and 100, so the code block inside the second else statement is executed, and the output will be “Value is between 51 und 100”.

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