Nested if
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A nested if is an if inside the block of another if. The inner question is asked only when the outer answer is true.
An if inside an if
An ATM asks for the amount only after the PIN is right; asking after a wrong PIN makes no sense. Put the second if inside the block of the first: a nested if.
Example 1 · ATM: PIN first, then balance
import java.util.Scanner;
public class Atm { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int balance = 3000; System.out.print("Enter PIN: "); int pin = sc.nextInt(); if (pin == 4321) { System.out.print("Amount: "); int amount = sc.nextInt(); if (amount <= balance) { System.out.println("Take your cash: Rs " + amount); System.out.println("Balance left: Rs " + (balance - amount)); } else { System.out.println("Low balance"); } } else { System.out.println("Wrong PIN"); } sc.close(); }}Enter PIN: 4321 Amount: 2000 Take your cash: Rs 2000 Balance left: Rs 1000
What this code does
- The PIN matches, so Java enters the outer block and only then asks for the amount. With a wrong PIN the amount is never asked.
amountis created inside the outer block, so it exists only there: using it after that block's}givescannot find symbol.
Each if can have its own else, so each failure gets its own message: Wrong PIN or Low balance.
Which else belongs to which if
In nested code, two else words can sit close together. Which question does each one answer?
An else belongs to the nearest if above it in the same block. The braces make the blocks, and indenting each level four more spaces makes them easy to see. Step through the program and watch which else runs.
Trace the code
Follow the two else blocks
Variables
- number
- 7
Output
(nothing printed yet)Line 3number starts at 7.
Nested if or &&
A canteen gives students Rs 50 off bills of Rs 500 or more. You can nest the bill check inside the student check, or join both with && as in Combine conditions (opens in a new tab).
Example 2 · Same rule, nested and with &&
public class Discount { public static void main(String[] args) { boolean isStudent = true; int bill = 800; if (isStudent) { if (bill >= 500) { System.out.println("Nested: discount Rs 50"); } } if (isStudent && bill >= 500) { System.out.println("With &&: discount Rs 50"); } }}Nested: discount Rs 50 With &&: discount Rs 50
What this code does
- Both versions give the discount only when both checks are
true. - With no inner
else, the&&version says the same thing in fewer lines.
Nest when each step needs its own message or action, like the ATM. Keep nesting to about two levels; deeper code is hard to follow, and && or an else-if ladder (opens in a new tab) can often flatten it.
Next step
Check your understanding
7 quick questions