Java Code Example: multi-branches

The MultiBranchesExample Java program demonstrates the use of an if-else if-else statement to conditionally execute code based on multiple conditions with user input.

In the program, a Scanner object is created to read input from the console. Then, two integer variables firstNumber and secondNumber are declared and initialized with user input using the nextInt() method of the Scanner class.

The if-else if-else statement checks the values of firstNumber and secondNumber and executes the appropriate code block based on the following conditions:

  • If firstNumber is greater than secondNumber, the code block inside the first if statement is executed, which prints a message indicating that firstNumber is greater than secondNumber.
  • If firstNumber is less than secondNumber, the code block inside the else if statement is executed, which prints a message indicating that firstNumber is less than secondNumber.
  • If firstNumber is equal to secondNumber, the code block inside the else statement is executed, which prints a message indicating that firstNumber is equal to secondNumber.
import java.util.Scanner;

public class MultiBranchesExample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int firstNumber, secondNumber;

        System.out.print("Please enter first number: ");
        firstNumber = scan.nextInt();
        System.out.print("Please enter second number: ");
        secondNumber = scan.nextInt();

        if (firstNumber > secondNumber) {
            System.out.print(firstNumber + " > " + secondNumber);
        } else if (firstNumber < secondNumber) {
            System.out.print(firstNumber + " < " + secondNumber);
        } else {
            System.out.print(firstNumber + " = " + secondNumber);
        }
    }
}
Output
Please enter first number: 4
Please enter second number: 4
4 = 4

In summary, the program demonstrates how to use an if-else if-else statement to conditionally execute code based on multiple conditions with user input, and how to read input from the console using the Scanner class.