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:
public class GFG{
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.
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."
Syntax of if-else Statement
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
Working of if-else Statement
1. Control falls into the if block.
2. The flow jumps to the condition.
3. The condition is tested:
- If the condition yields true, go to Step 4.
- If the condition yields false, go to Step 5.
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.
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) {
if (condition2) {
// Executes when both condition1 and condition2 are true
}
}
Example:
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.
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