if Statement
The if
statement in Java is a conditional statement that allows you to execute a block of code based on the evaluation of a boolean expression. If the boolean expression is true, the block of code inside the if
statement is executed; otherwise, it is skipped.
Example:
public class IfStatementExample {
public static void main(String[] args) {
int x = 10;
// Simple if statement
if (x > 5) {
System.out.println("x is greater than 5");
}
// If-else statement
if (x > 20) {
System.out.println("x is greater than 20");
} else {
System.out.println("x is not greater than 20");
}
// If-else if-else statement
if (x > 15) {
System.out.println("x is greater than 15");
} else if (x > 10) {
System.out.println("x is greater than 10 but not 15");
} else {
System.out.println("x is 10 or less");
}
}
}
In this example:
- The first
if
statement checks ifx
is greater than 5 and prints a message if true. - The second
if-else
statement checks ifx
is greater than 20 and prints a message accordingly. - The third
if-else if-else
statement checks multiple conditions and prints messages based on the evaluation of these conditions.
You can have multiple else if
blocks to check additional conditions. The if
statement allows you to control the flow of your program based on different conditions. Keep in mind that only the block of code associated with the first true condition (or the first if
or else if
block with a true condition) will be executed.