if..else..if Loader


Syntax:

if(condition-1)
{
   //Statements which will be executed if condition-1 is true
}

else if (condition-2)
{
   //Statements which will be executed if condition-2 is true
}
.
.
.
.else if (condition-n)
{
   //Statements which will be executed if condition-n is true
}

else
{
   //Statements which will be executed if none of the conditions in condition-1, condition2,…condition-n are true.
}
   //Statements which will be executed always


  • As you can see in this if-else-if ladder, conditions are evaluated from top.
  • First condition-1 will be evaluated and if this is true, the code inside the if block will be executed. If condition-1 is false, condition-2 will be evaluated.
  • If condition-2 is true, the code inside that else if block will be executed. If condition-2 is false, condition-3 will be evaluated. This will go on like this.
  • If none of the conditions are true, the code inside the else block will be executed.

Example:

We can take a look on a program which will

  1. display a message “Hello” if a particular value is equal to 1.
  2. display a message “Hi” if a particular value is equal to 2.
  3. display a message “Good” if a particular value is equal to 3.
  4. display a message “No Match Found” if none of the above conditions are matchin
/*
* FileName :  IfElseIfLadderDemo1.java
*/

public class IfElseIfLadderDemo1
{
    public static void main(String args[])
    {
        //Declaring a variable "test" and initializing it with a value 2
        int test=2;

        if(test==1)
        {
            //This block will be executed only if "test" is equal to 1
            System.out.println("Hello");
        }
        else if(test==2)
        {
            //This block will be executed only if "test" is equal to 2
            System.out.println("Hi");

        }
        else if(test==3)
        {
            //This block will be executed only if "test" is equal to 3
            System.out.println("Good");
        }
        else
        {
            System.out.println("No Match Found");
        }
    }
}



Output:
Hi

This program outputs the message “Hi” because the declared variable “test” has a value 2.


Popular posts from this blog

Naming Conventions

Nested if..else Statement