if…..else if Statement

 

if…..else if Statement

But what if we have more than two blocks of code? And what if we need to check which block of code evaluates to true? Well here we use an if…..else if statement.

if……else if statements allows us to check multiple expressions and enter the block of code where the condition evaluates to true.

Syntax:

if (condition 1) {
    //block of code
} else if (condition 2) {
    //block of code
} else if (condition 3) {
    //block of code
} else if (condition 4) {
    //block of code
} else {
    //if no condition matches
    //block of code
}

 

Example:

public class JavaIf {
    public static void main(String[] args) {
        String name[] = {"Maxon", "Kapil", "Sonu"};
        int Roll[] = {25, 36, 71};
        if (name[0] == "Maxon" && Roll[1] == 25) {
            System.out.println("Details of Maxon.");
        } else if (name[2] == "Kapil" && Roll[1] == 36) {
            System.out.println("Details of Kapil.");
        } else if (name[2] == "Sonu" && Roll[2] == 71) {
            System.out.println("Details of Sonu.");
        } else {
            System.out.println("Invalid details.");
        }
    }
}

 

Output:

Details of Sonu.