The if...else...if Ladder


Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if ( condition )
  statement;
else if ( condition )
  statement;
else if ( condition )
  statement;
  .
  .
else
  statement;

IfElseIfDemo1.java (the if...else...if statement)
class IfElseIfDemo1 {
  public static void main( String args[ ] ) {
    Double    x =  20.0;
    if      ( x == 20 )  System.out.println( 1 );
    else if ( x >  20 )  System.out.println( 2 );
    else                 System.out.println( 3 );
  }
}
Output:             Result:

IfElseIfDemo2.java (the if...else...if statement)
// Java program to illustrate if...else...if ladder
class IfElseIfDemo2 { 
  public static void main( String args[ ] ) { 
    int i = Integer.parseInt( args[0] ); 
    if ( i == 0 )
      System.out.print( 1 );
    else if ( i < 2 )
      System.out.print( 2 );
    else
      if ( i < 3 )
        System.out.print( 3 );
      if ( i < 4 )
        System.out.print( 4 );
      else
        System.out.print( 5 );
  } 
}
shell> java IfElseIfDemo2  

Output:           Result:




      Actions speak louder than words.