ELSE IF Ladder in Java


Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

The else if condition is checked only if all the conditions before it (in previous else if constructs, and the parent if constructs) have been tested to false.

Example: The else if condition will only be checked if i is greater than or equal to 2.

  • If its result is true, its block is run, and any else if and else constructs after it will be skipped.
  • If none of the if and else if conditions have been tested to true, the else block at the end will be run.

 Syntax :
   if ( condition 1 )
   {
       // block of statement to be executed if condition is true ;
   }
   else if ( condition 2 )
   {
       // block of statement to be executed if the condition1 is false condition2 is true ;
   }
   else
   {
       block of statement to be executed if the condition1 is false condition2 is False ;
   }

Source Code

import java.util.Scanner;
 
/*
Else If Ladder
90-100 Grade-A
80-89  Grade-B
70-79  Grade-C
<70    Grade-D
*/
public class else_if {
    public static void main(String args[]) {
        float avg;
        System.out.println("Enter The Average Mark : ");
        Scanner in = new Scanner(System.in);
        avg = in.nextFloat();
        if (avg >= 90 && avg <= 100) {
            System.out.println("Grade A");
        } else if (avg >= 80 && avg <= 89) {
            System.out.println("Grade B");
        } else if (avg >= 70 && avg <= 79) {
            System.out.println("Grade C");
        } else {
            System.out.println("Grade D");
        }
    }
}
 
 

Output

Enter The Average Mark :
84
Grade B
To download raw file Click Here
`

Basic Programs