Java Else-If Statement

18-Sep-2024

Learn how to use the else-if statement for more complex decision-making in Java.



In the else-if control statement. Code will be executed based on multiple conditions. When we need to work with multiple conditions then we use else-if statements.


Syntax :



if(condition) {

// if the condition is true then this block of code will execute

}
else if(condition2){

// if the condition 2 is true then this block of code will execute

}
else{

// if all the conditions are false then the else block will be executed

}



Flow Chart:





 Example:



import java.util.Scanner;
public class ifest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();

      if(age < 18){

      System.out.println("teenager");

}
else if(age >= 18 && age <= 60){

      System.out.println("adult");

}
else{

     System.out.println("senior citizen);

   }

    }

}
     


In this example, if the age is less than 18 (the condition will be true) then the if block will execute otherwise the else if condition will be tested. If age is greater than or equal to 18 and less than or equal to 60 (condition will be true) then the else if block will be executed. If all the conditions are false then the else block will be executed.


Comments