If Else Statement in Java

It is used to check condition and execute code. But if that condition fails, this statement have backup plan called else. Program in else block will be executed if condition does not meets. Syntax:

if (condition)
    single line true statement;
else
    single line false statement;
or
if (condition) {
    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.


Examples:

Code:

public class LearnIfElse { public static void main(String[] args) { int x = 4; int y = 3; if (x == y) System.out.println("They are same."); else System.out.println("They are different."); } }
Output:
They are different.

Code:

public class LearnIfElse { public static void main(String[] args) { int age = 20; if (age > 18) System.out.println("You can vote."); else System.out.println("You cannot vote."); } }
Output:
You can vote.

Code:

public class LearnIfElse { public static void main(String[] args) { String user = "bcaboost"; if (user == "bcaboost") System.out.println("Welcome BCA Boost."); else System.out.println("Invalid User!"); } }
Output:
Welcome BCA Boost.


If Statement in Java Previous Next If Else If Statement in Java