If Statement in Java

In Java, we can use if statements to check certain conditions and execute the code if that condition is valid. Also we can check for another condition if first condition fails. It is as easy as it sounds.

It comes handy if we have to check a condition and execute code. It is simple and easy to use. If checks a condition and executes code quickly. Syntax:

if (condition)
    single line true statement;
or
if (condition) {
    true 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 LearnIf { public static void main(String[] args) { if(4 > 2) System.out.println("Yeah! It is."); } }
Output:
Yeah! It is.

Code:

public class LearnIf { public static void main(String[] args) { int x = 5; int y = 2; if(x > y) System.out.println("x is greater than y"); } }
Output:
x is greater than y


Decision Making in Java Previous Next If Else Statement in Java