Understanding Java Conditional Statements
In Java, conditional statements allow you to control the flow of your program based on certain conditions. The most
common conditional statements are the if, else if, and else statements.
if Statement:
The if statement is used to execute a block of code if a specified condition evaluates to true.
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}
else if Statement:
The else if statement is used to test multiple conditions. If the preceding if statement
or else if statements evaluate to false, the code within the block of the first true condition is executed.
int y = 7;
if (y > 10) {
System.out.println("y is greater than 10");
} else if (y > 5) {
System.out.println("y is greater than 5");
} else {
System.out.println("y is 5 or less");
}
else Statement:
The else statement is used to execute a block of code if none of the preceding conditions in the
if and else if statements are true.
int z = 3;
if (z > 5) {
System.out.println("z is greater than 5");
} else {
System.out.println("z is 5 or less");
}
Example:
Here's an example demonstrating the use of conditional statements in Java:
int number = 8;
if (number % 2 == 0) {
System.out.println("The number is even");
} else {
System.out.println("The number is odd");
}
Note:
Conditional statements are crucial for making decisions in your Java programs. They allow you to execute different blocks of code based on varying conditions.