if-else-if ladder Statement in Java


If you have more than two conditions to test, then use if-else-if.

☞If the condition evaluates to true, it executes the statements of if block, otherwise control reaches to else part but if you want to check condition in else part then you will have to write else if and so on.

☞Syntax :

if(condition) {
    Statement 1
    Statement 2
    ...........
}
else if(condition) {
    Statement 1
    Statement 2
    ...........
}
else if(condition) {
    Statement 1
    Statement 2
    ...........
}
else {
    Statement 1
    Statement 2
    ...........
}

Example

/*Finding number is positive, negative or zero
number>0 is positive, number<0 is negative*/
import java.util.*;

public class IfElseIfExample {
public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter a number");
    int num=sc.nextInt();
    
    if(num>0)
        System.out.println("Positive number");
    
    else if(num<0)
        System.out.println("Negative number");
    
    else
        System.out.println("Zer0");

}
}

Output

Enter a number
-6
Negative number

Rule : Whenever there are more than one statement in if or else block, then these statements must be in curly braces.