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