Java Code Example: multi-branches

In Java there are also multiple branches represented by the else if statement

The if-conditions are evaluated in sequence until one of them is true. Then finally the code section belonging to this condition is executed and the multiple branching handling is finished. The else-part is only executed if none of the conditions is true.

Code Explanation

LineDescription
1Import java Scanner class to accept user input
5Creates an object of the Scanner class named scan and assigns it a predefined standard input object
6Creates two variables of type integer with the names firstNumber and secondNumber
8Prompts the user to enter the first number
9Calls the nextInt() method of the scan object and uses it to retrieve the user input. Then the input is stored in the variable firstNumber
10Prompts the user to enter the second number
11Calls the nextInt() method of the scan object and uses it to retrieve the second user input. Then the input is stored in the variable secondNumber
13 – 14If the value of the variable firstNumber is greater than the value of the variable secondNumber, the string “value_first_variable > value_second_variable” is output
15 – 16If firstNumber is smaller than secondNumber, the string “value_first_variable < value_second_variable” is output
17 – 18Otherwise the string “value_first_variable = value_second_variable” is output
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