If else ladder in Java

If else ladder in Java

We now know that using the if-else statements, we can just do something, on the basis of some condition. But at times, things can go a bit complicated. We have seen that with it, we check the condition.

Also, there can be some complicated conditions. Let’s say that some condition gets false, and we move to the else part. But now, we again need to check some conditions. But how are we going to do this? Because we do not write condition after else. In such a situation, we can use if after else, to specify the condition. This is like else, again check some conditions. Let’s understand this with an example. This is often also called an if-else ladder.

public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“1. Coffee\n2.Tea\n3.Milk choose your drink: “);
int drinkChoice = scanner.nextInt();
if (drinkChoice == 1)
System.out.println(“Coffee”);
else if (drinkChoice == 2)
System.out.println(“Tea”);
else if (drinkChoice == 3)
System.out.println(“Milk”);
else
System.out.println(“Invalid choice!”);
}
}

As you can see, we could check the condition after else as well, because we were using the if statement after the else statement. In the above program, we are asking the user for input, like for coffee, tea, or milk, and accordingly, we are checking the output. So, you can use the if-else ladder as and when required.