If Else If Statement in Java

It is used to check multiple conditions and execute code. if first condition fails, this statement checks another condition called else if. Lastly we have else block which will be executed if any of above conditions does not meet. Syntax:

if (condition)
    single line true statement;
else if (condition 2)
    single line second true statement;
else
    false statement
or
if (condition) {
    true statements;
    where statement can be
    more than one line
}
else if (condition 2) {
    second true statements;
    where statement can be
    more than one line
}
else {
   false statements;
    where statement can be
    more than one line
}
As you can see above, we can directly write our statement if our code is in single line. But we have to wrap all code in curly braces if our code have have multiple lines. We can repeat else if block as many times we have to check conditions.


Examples:

Code:

public class LearnIfElseIf { public static void main(String[] args) { int a = 4; int b = 5; if (a > b) System.out.println("A is greater."); else if (a < b) System.out.println("B is greater."); else System.out.println("They are equal."); } }
Output:
B is greater.

Code:

public class LearnIfElseIf { public static void main(String[] args) { int a = 9; int b = 5; int c; if (a > b) { c = a - b; } else if (a < b) { c = b - a; } else { c = 0; } System.out.println("Difference between these digits: " + c); } }
Output:
Difference between these digits: 4


If Else Statement in Java Previous Next Switch Case in Java