Skip to main content

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.
Tags
Submitted by arilio666 on October 21, 2021

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.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.