Java Nested If
Sometimes one decision only makes sense after another has already been answered. A nested if is simply an if (or if...else) statement placed inside the body of another if. This lets you drill down through layered conditions, though it also brings a risk of hard-to-read code if you overdo it.
What nesting means
When you put an if statement inside another if statement, the inner condition is only ever checked if the outer condition was true. This models situations where a second question depends on the answer to a first one, such as: is the user logged in, and if so, are they an administrator?
A nested if in action
public class Main {
public static void main(String[] args) {
boolean loggedIn = true;
boolean isAdmin = false;
if (loggedIn) {
System.out.println("Welcome back!");
if (isAdmin) {
System.out.println("You have admin tools.");
} else {
System.out.println("You have standard access.");
}
} else {
System.out.println("Please log in first.");
}
}
}
// Output:
// Welcome back!
// You have standard access.A practical example
Imagine deciding whether someone can ride a roller coaster. First you check their age, and only for the right age group do you then check their height. The inner check never runs for people who fail the outer check, which keeps the logic focused.
Ride eligibility
public class Main {
public static void main(String[] args) {
int age = 12;
int heightCm = 150;
if (age >= 10) {
if (heightCm >= 140) {
System.out.println("You can ride the coaster.");
} else {
System.out.println("You meet the age but not the height.");
}
} else {
System.out.println("You are too young for this ride.");
}
}
}
// Output:
// You can ride the coaster.When to combine instead of nest
If both conditions must be true and neither branch has its own separate else logic, you can often flatten the nesting into a single if using the logical AND operator &&. This keeps the code shorter and easier to follow.
- Use nesting when the inner decision has its own else branch or extra steps.
- Use && to merge conditions when you only care about the case where all of them are true.
- Consider returning early from a method to avoid wrapping the rest of the code in another level.
Flattening with the && operator
public class Main {
public static void main(String[] args) {
int age = 12;
int heightCm = 150;
if (age >= 10 && heightCm >= 140) {
System.out.println("You can ride the coaster.");
} else {
System.out.println("Sorry, you cannot ride yet.");
}
}
}
// Output:
// You can ride the coaster.