AI Hints
Home›Java Tutorial›Switch Expressions, Nested Decisions, Practice: Grade Checker
Java · Lesson 35 of 120

Nested Decisions

If inside if.

⏱ 2 min read▶ Video at 44:57🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Sometimes a decision depends on another decision. You can put an if, inside another if. That's called nesting.

  • A decision inside
  • Another decision
  • Called nesting

An if inside an else

If you're eighteen or older, you can watch. Otherwise, a second question, is a parent with you? The inner if only runs when the outer condition is false. Run it. Sixteen, with a parent, so you can watch it with your parent.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int age = 16;
        boolean withParent = true;
        if (age >= 18) {
            System.out.println("You can watch the film.");
        } else {
            if (withParent) {
                System.out.println("You can watch it with your parent.");
            } else {
                System.out.println("Sorry, you're too young.");
            }
        }
    }
}
Output
You can watch it with your parent.

Flatter is clearer

The same logic, without nesting. Else if, with parent, replaces the inner if. It does exactly the same thing, but it's easier to read. Run it. Same answer.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int age = 16;
        boolean withParent = true;
        if (age >= 18) {
            System.out.println("You can watch the film.");
        } else if (withParent) {
            System.out.println("You can watch it with your parent.");
        } else {
            System.out.println("Sorry, you're too young.");
        }
    }
}
Output
You can watch it with your parent.

Keeping it readable

Deep nesting is hard to follow. Combine conditions with and, when you can. Use else if chains, instead of if inside else. And check the special cases first.

keyvalue
Avoiddeep nesting
Combinewith && and ||
Preferelse if chains
Firstcheck special cases

Summary

You can put if inside if, but flatter code is easier to read. Next, a practice grade checker.

Key takeaways
  • if inside if
  • Prefer else if
  • Keep it flat
Next up: Practice: Grade Checker — put module four together