![]() |
VOOZH | about |
The if-else statement in Java is a decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false.
Example:
The number is greater than 5.
Explanation: The program declares an integer n and checks if it is greater than 5 using an if-else statement. Based on the condition, it prints either "The number is greater than 5." or "The number is 5 or less."
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
1. Control falls into the if block.
2. The flow jumps to the condition.
3. The condition is tested:
4. The if block or the body inside the if is executed.
5. If the condition is false, the else block is executed instead.
6. Control exits the if-else block.
Below is the Java if-else flowchart.
In the above flowchart of Java if-else, it states that the condition is evaluated, and if it is true, the if block executes; otherwise, the else block executes, followed by the continuation of the program.
In Java, we can use nested if statements to create more complex conditional logic. Nested if statements are if statements inside other if statements.
if (condition1) {
if (condition2) {
// Executes when both condition1 and condition2 are true
}
}
Example:
You are eligible to donate blood.
Explanation: The program uses a nested if statement to check a personโs age and weight for blood donation eligibility. It prints messages based on whether the age is at least 18 and the weight is at least 50 kilograms.
Note: In Java, an else statement always pairs with the nearest unmatched if statement