Java if-else Statement
The if-else statement in Java is a powerful 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. In this article, we will learn Java if-else statement with examples.
Example:
// Java Program to demonstrate
// if-else statement
public class IfElse {
public static void main(String[] args) {
int n = 10;
if (n > 5) {
System.out.println("The number is greater than 5.");
} else {
System.out.println("The number is 5 or less.");
}
}
}
Output
The number is greater than 5.
Dry-Running the Above Example:
- Program starts.
nis initialized to10.ifcondition is checked:10 > 5, yieldstrue.- Block inside the
ifstatement executes:"The number is greater than 5."is printed.
- Block inside the
- The
elseblock is skipped as the condition istrue.
Syntax of if-else Statement
if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }
Working of if-else Statement
- Control falls into the
ifblock. - The flow jumps to the condition.
- The condition is tested:
- If the condition yields
true, go to Step 4. - If the condition yields
false, go to Step 5.
- If the condition yields
- The
ifblock or the body inside theifis executed. - If the condition is
false, theelseblock is executed instead. - Control exits the
if-elseblock.
Flowchart of Java if-else Statement
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.
Nested if statement in Java
In Java, we can use nested if statements to create more complex conditional logic. Nested if statements are if statements inside other if statements.
Syntax of Nested if
if (condition1) { // code block 1 if (condition2) { // code block 2 } }
Example:
// Java Program to implement
// Nested if statement
public class NestedIf {
public static void main(String[] args) {
int a = 25;
double w = 65.5;
if (a >= 18) {
if (w >= 50.0) {
System.out.println("You are eligible to donate blood.");
} else {
System.out.println("You must weigh at least 50 kilograms to donate blood.");
}
} else {
System.out.println("You must be at least 18 years old to donate blood.");
}
}
}
Output
You are eligible to donate blood.
Note: The first print statement is in a block of "if" so the second statement is not in the block of "if". The third print statement is in else but that else doesn't have any corresponding "if". That means an "else" statement cannot exist without an "if" statement.