Java Decision Making Statement

java if-else-if statement

In case we have several options available, we can use if-else-if statement to choose one among them that passes the test condition.
Each if statement will be tested sequentially from top till the end untill one is found to be true.
If none of if statement executes to true then the else statement at the end will get executed.
Syntax of if-else-if
  //code to execute
}else if(condition1){
 //code to execute
}else if(condition2){
   ….//100 or 1000 more ladders of if-else-if in between
}else if(condition100){
 //code to execute
 //code to execute

From above syntax it is clear that if our first conditions fails then next condition in else if will be checked for and will go on until it executes to true or reaches the else statement given at the last.
Example: If I reach bus stop before 9:00AM then I will take public bus else I will book Ola or Uber after comparing their fare.
import java.util.Scanner;

public class UseIf {

    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter time:");
      int time = sc.nextInt();
      int olaFare = 101, uberFare = 100;

        System.out.println("Take public bus as transport");
      }else if(olaFare==uberFare){
        System.out.println("Book whichever has minimum pick up and drop time");
      }else if(olaFare>uberFare){
        System.out.println("Book Uber");
        System.out.println("Book ola");



Enter time:
Book Uber
We have tested our code based on three conditions in above example. Similarly we can have more test conditions in between.


Drawback of if-else-if statement

In case we have many test conditions, our if-else-if ladder will grow up to be very large and will become untidy and difficult to manage the code.

Solution to the drawback

Switch-case will help solve the above problem. Let’s learn more about it in next section.

Please Share this page
Views : 65
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!