Java: if-else-if ladder

A control flow statement in java called the if-else if ladder is nothing but a series of conditions to satisfy.

  • These conditions are given in the if block and followed by the else if block which can be given in many terms without any restriction.
  • If all the conditions of the else if ladder fails eventually the last else block will be executed.

Syntax

If(conditon)
{
    //statement 1
}
else if (condition)
{
    //statement 2
}
else
{
    //statement 3
}

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 2, val3, val4 = 10, val5;
        
        if ((val2 + val1) == val4)
        {
            System.out.println("Equal");
        }
        else if ((val2 + val1) != val4)
        {
            System.out.println("Not Equal");
        }
        else
        {
            System.out.println("Both conditions Failed");
        }
    }
}

Output: Not Equal

  • From the code, val4 is 10 and is not equal to the sum of val1 and val2 so if block failed and since the else if block satisfied the condition.
  • Its body got executed terminating the block from here and proceeding further after the code.
Thu, 10/21/2021 - 14:58

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags