Website For Developers

If-elseif in Java



Syntax

if (Condition 1)
{
// Executes if Condition 1 is true
}
else if (Condition 2)
{
// Executes if Condition 2 is true
}
else if (Condition 3)
{
// Executes if Condition is true
}
else
{
// Executes when all Conditions are false
}


Example of if-elseif statement in Java

public class ElseIfTopic{

   public static void main(String[] args) {
     int i = 3;
     if(i == 1){
       System.out.println( "Condition one is true!" );
     }

     else if(i == 2){
       System.out.println( "Condition two is true!" );
     }

     else if(i == 3){
       System.out.println( "Condition three is true!" );
     }
     else{
       System.out.println( "All Conditions are false!" );
     }
   }
}

Output

Condition three is true!



Nested if-else Statement


Syntax

if (Condition)
{
// Outer if body
if (Condition)
{
// Inner if body
}
}
else ()
{
// else body
}


Working of Nested if statement


Example of nested if Statement

public class NestedIf{

   public static void main(String[] args) {
     String color = "White";
     int size = 27;
     if(size == 27){
       System.out.println( "Football size is 27 inches." );
       if("white".equals(color)){ // Inner If Condition
         System.out.println( "Football size is 27 inches and color is White." );
       }
     }
     else{
       System.out.println( "Size is not equals to 27 inches" );
     }
   }
}

Output

Football size is 27 inches.
Football size is 27 inches and color is White.