Careeroza
The if Statement
Syntax
The if statement runs a block of code only when a condition is true.
if (condition) {
// runs when condition is true
}Example
Example
public class Main {
public static void main(String[] args) {
int temperature = 38;
if (temperature > 35) {
System.out.println("It is very hot today. Stay hydrated!");
}
int balance = 200;
if (balance < 500) {
System.out.println("Low balance alert");
}
System.out.println("Program finished");
}
}Output
It is very hot today. Stay hydrated! Low balance alert Program finished
Note: If the block has a single statement you may leave out the braces, but always using { } avoids bugs when someone adds a second line later.
Common Mistake
int x = 5;
if (x = 10) { } // compile error: int cannot be converted to boolean
if (x == 10) { } // correct: comparison
if (x > 3); { // the ; ends the if! the block always runs
System.out.println("always printed");
}