if…else Statement
The if...else
statement in Java provides a way to execute different blocks of code based on the evaluation of a boolean expression. If the boolean expression in the if
statement is true, the code inside the if
block is executed. If the expression is false, the code inside the else
block is executed.
Example:
public class IfElseStatementExample {
public static void main(String[] args) {
int x = 10;
// If-else statement
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is 5 or less");
}
// Another example
int y = 7;
if (y % 2 == 0) {
System.out.println("y is an even number");
} else {
System.out.println("y is an odd number");
}
}
}
In this example:
- The first
if...else
statement checks ifx
is greater than 5 and prints a message accordingly. - The second
if...else
statement checks ify
is an even or odd number based on the remainder when divided by 2.
You can have multiple else if
blocks to check additional conditions. The if...else
statement allows you to handle scenarios where there are two possible outcomes based on the evaluation of a condition. The code inside the else
block is executed only if the condition in the if
statement is false.