else if ladder in Java

Else if ladder similar to if else statements are used when we have many number of conditions.

General Syntax for else-if

if(condition or expression) {

//body or statements

}

else if(condition or expression){

//body or statements

}

else {

//body or statements

}

If any of the condition returns true, their respective body will be executed. The check is done one by one from top, if true the respective body will be executed and check stops.

Imagine as you forgot your car key where you kept in home. You will search places one by one for the key in the home. Right ?

How will you solve this using programming ?

Imagine key as one variable and places as array variable.

Solve like this below,

public class ElseIfTest {

public static void main(String args[]) {

int key=1,places[]={0,1,3};

if(key==places[0]){

System.out.println("Key available in 1st place");

}

else if(key==places[1]) {

System.out.println("Key available in 2nd place");

}

else if(key==places[2]){

System.out.println("Key available in 3rd place");

}

}

}

}

Try In Editor

Output

Key available in 2nd place