Part 03 / Stage 1
Control flow
Goal: Make decisions (
if/else,switch) and repeat work (while,for,for-each) in a Java program, and know exactly when to stop or skip a loop iteration withbreak/continue. Time: ~5 hours
What you will learn
if/else, else-if ladders, nested conditionals, and the?:ternary operator- The classic
switchstatement (case/break) and why a missingbreakfalls through - The arrow
switchexpression (case ... ->),yield, and when to pick it over the classic form whileloops, including the "ask until correct or out of attempts" shapeforloops, including nested loopsfor-eachloops — a preview, since the array type itself is Part 4's lessonbreakandcontinue, and the one mistake almost everyone makes withbreakinside aswitch- Putting all of it together: an ATM menu with 3 PIN attempts
About the code style here: every example in this part lives entirely inside
main. Java always needs a class and a method to run at all, but writing your own methods (beyondmain) is Part 5's topic. So instead of helper methods, each example uses a plain{ }block to keep one demo's variables from colliding with the next one's — nothing more than that.
Topics in this part
Practice
Write each answer in its own file as a single class with a main method — no other methods yet, that is Part 5. Use Scanner for any input, exactly as in examples/. Where an exercise says "pick a fixed value", put it straight in the code (a literal), the same way the examples do; you do not need command-line arguments.
Exercise 1: Loan eligibility (nested if/else)
Scenario: A Pune co-operative bank gives a personal loan only if the applicant is at least 21 years old and earns at least Rs 25,000 a month. Someone who is old enough but earns less gets a smaller, flagged loan instead of a flat rejection.
What to do: In main, set int age = 19; and int monthlyIncome = 30000;. Using nested if/else (an if inside an if, like examples/01_if_else.java):
- If
age < 21, printNot eligible: age below 21. - Else if
monthlyIncome < 25000, printNot eligible: income below Rs 25000. - Else, print
Eligible for the full loan amount.
Run it once with the values above, then change age to 22 and run again.
Sample output (age = 19):
Not eligible: age below 21.
Sample output (age = 22):
Eligible for the full loan amount.
💡 Hint: check age first — if that check already fails, the income branch never needs to run.
Exercise 2: Weekday or weekend (classic switch)
Scenario: An ATM shows a different daily withdrawal limit on weekends.
What to do: In main, set int dayNumber = 7; (1 = Monday … 7 = Sunday). Write a classic switch statement (case/break, like examples/02_switch_statement_and_expression.java) that prints:
Weekday limit: Rs 25000for 1–5Weekend limit: Rs 40000for 6 or 7Invalid dayfor anything else
Group cases 1–5 together and 6–7 together (no repeated System.out.println lines).
Sample output:
Weekend limit: Rs 40000
💡 Hint: stack case 1: through case 5: with no break between them, so they all fall through to one println + break.
Exercise 3: Transaction fee (arrow switch expression)
Scenario: The same bank charges a flat fee per withdrawal, based on how the customer withdraws.
What to do: In main, set String channel = "ATM";. Write an arrow switch expression (like examples/02_switch_statement_and_expression.java) that assigns an int fee to a variable:
"ATM"→20"Branch"→0"Online"→5- anything else →
50
Print Fee for <channel>: Rs <fee>. Then explain, in a one-line code comment above the switch, why an arrow expression fits here better than a classic switch statement (each branch only produces one value).
Sample output:
Fee for ATM: Rs 20
💡 Hint: int fee = switch (channel) { case "ATM" -> 20; ... }; — the whole thing is one assignment, no break anywhere.
Exercise 4: Countdown before a transaction (while loop)
Scenario: Before processing a large withdrawal, the ATM screen counts down from a starting number of seconds.
What to do: In main, set int secondsLeft = 5;. Using a while loop (like examples/03_while_loops.java), print each value of secondsLeft followed by ..., then decrease it by 1, until it reaches 0. After the loop, print Processing....
Sample output:
5...
4...
3...
2...
1...
Processing...
💡 Hint: the loop condition is secondsLeft > 0; decrease secondsLeft as the last thing inside the loop body.
Exercise 5: Interest schedule (for loop)
Scenario: A recurring deposit of Rs 2,000 a month, for 4 months, with the running total printed after each deposit.
What to do: In main, set int monthlyDeposit = 2000; and int months = 4;. Using a classic for loop (like examples/04_for_loops.java), print, for each month from 1 to months, a line Month <n>: total Rs <runningTotal>.
Sample output:
Month 1: total Rs 2000
Month 2: total Rs 4000
Month 3: total Rs 6000
Month 4: total Rs 8000
💡 Hint: declare int runningTotal = 0; before the loop, and do runningTotal += monthlyDeposit; as the first line inside it.
Exercise 6: Average of fixed-deposit amounts (for-each preview)
Scenario: A branch manager has five fixed-deposit amounts (in rupees) and wants the total and the average, printed to the rupee.
What to do: In main, declare int[] deposits = {15000, 22000, 18500, 9000, 12500}; (the same minimal array-literal syntax as examples/05_for_each_preview.java — the array type itself is Part 4's lesson). Use a for-each loop to add every value into a running total, then print the total and the average (integer division is fine).
Sample output:
Total: 77000
Average: 15400
💡 Hint: for (int deposit : deposits) { total += deposit; }, then total / deposits.length.
Exercise 7: Skip invalid entries, stop at a sentinel (break + continue)
Scenario: A batch of cheque amounts has some bad entries (zero or negative, meaning "cheque bounced, ignore it") and ends with a special value -999 meaning "end of batch, stop reading, even if more values follow."
What to do: In main, declare int[] cheques = {4000, -1, 7000, 0, 9500, -999, 3000};. Loop over it with for-each:
- If the value is
-999, printEnd of batch.and stop the loop completely. - Else if the value is
<= 0, skip it (do not add it, do not print anything for it) and move to the next value. - Else, add it to a running total and print
Added <value>, total so far: <runningTotal>.
Print the final total after the loop. Note that 3000, after the -999, must never be processed.
Sample output:
Added 4000, total so far: 4000
Added 7000, total so far: 11000
Added 9500, total so far: 20500
End of batch.
Final total: 20500
💡 Hint: check for -999 first and break; check for <= 0 next and continue; everything else falls through to the "add it" case.
Exercise 8: ATM menu with 3 PIN attempts (the capstone)
Scenario: This is the part's full capstone, the same shape as examples/07_atm_menu.java, but with your own numbers so you are not just retyping the example.
What to do: In main:
- Set
final String correctPin = "7733";andint attemptsLeft = 3;. Using awhileloop andScanner, askEnter 4-digit PIN:and read a line. If it matches, unlock; otherwise reduceattemptsLeftand print how many attempts are left, orCard blocked.if it reaches 0. Stop asking once unlocked or blocked. - If unlocked, start with
double balance = 8000.0;and run a menu loop (while+ a classicswitch, like the example) offering:1. Check balance— print the balance.2. Deposit— ask for an amount; reject it (print a message, change nothing) if it is<= 0; otherwise add it and print the new balance.3. Withdraw— ask for an amount; reject it if it is<= 0or bigger than the balance (print which problem it was); otherwise subtract it and print the new balance.4. Exit— print a goodbye message and stop the menu loop (use aboolean runningflag, not a barebreak, sincebreakalone only exits theswitch).
- If blocked after 3 attempts, the program must end without ever showing the menu.
Run it twice: once where the 3rd attempt is correct, once where all 3 attempts are wrong.
Sample output (3rd attempt correct, then check balance, deposit 2000, withdraw 1500, exit):
Enter 4-digit PIN: Wrong PIN. Attempts left: 2
Enter 4-digit PIN: Wrong PIN. Attempts left: 1
Enter 4-digit PIN: PIN correct.
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose an option: Balance: Rs 8000.0
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose an option: Deposit amount: Rs Deposited Rs 2000.0. New balance: Rs 10000.0
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose an option: Withdraw amount: Rs Withdrew Rs 1500.0. New balance: Rs 8500.0
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose an option: Goodbye.
Sample output (all 3 attempts wrong):
Enter 4-digit PIN: Wrong PIN. Attempts left: 2
Enter 4-digit PIN: Wrong PIN. Attempts left: 1
Enter 4-digit PIN: Wrong PIN. Card blocked.
💡 Hint: structure it as two separate loops, one after the other: the PIN loop, then if (unlocked) { ... menu loop ... }. The menu loop never runs if the PIN loop ends with unlocked still false.
Show the solutions for Part 3 (8 files)
solutions/ex01.java
/*
* Exercise 1: Loan eligibility (nested if/else).
* Run: javac ex01.java && java Ex01
*/
class Ex01 {
public static void main(String[] args) {
int age = 19;
int monthlyIncome = 30000;
if (age < 21) {
System.out.println("Not eligible: age below 21.");
} else if (monthlyIncome < 25000) {
System.out.println("Not eligible: income below Rs 25000.");
} else {
System.out.println("Eligible for the full loan amount.");
}
}
}
solutions/ex02.java
/*
* Exercise 2: Weekday or weekend (classic switch).
* Run: javac ex02.java && java Ex02
*/
class Ex02 {
public static void main(String[] args) {
int dayNumber = 7;
switch (dayNumber) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday limit: Rs 25000");
break;
case 6:
case 7:
System.out.println("Weekend limit: Rs 40000");
break;
default:
System.out.println("Invalid day");
}
}
}
solutions/ex03.java
/*
* Exercise 3: Transaction fee (arrow switch expression).
* Run: javac ex03.java && java Ex03
*/
class Ex03 {
public static void main(String[] args) {
String channel = "ATM";
// an arrow switch expression fits here: every branch just produces
// one int value, there is no action to perform per case.
int fee = switch (channel) {
case "ATM" -> 20;
case "Branch" -> 0;
case "Online" -> 5;
default -> 50;
};
System.out.println("Fee for " + channel + ": Rs " + fee);
}
}
solutions/ex04.java
/*
* Exercise 4: Countdown before a transaction (while loop).
* Run: javac ex04.java && java Ex04
*/
class Ex04 {
public static void main(String[] args) {
int secondsLeft = 5;
while (secondsLeft > 0) {
System.out.println(secondsLeft + "...");
secondsLeft--;
}
System.out.println("Processing...");
}
}
solutions/ex05.java
/*
* Exercise 5: Interest schedule (for loop).
* Run: javac ex05.java && java Ex05
*/
class Ex05 {
public static void main(String[] args) {
int monthlyDeposit = 2000;
int months = 4;
int runningTotal = 0;
for (int month = 1; month <= months; month++) {
runningTotal += monthlyDeposit;
System.out.println("Month " + month + ": total Rs " + runningTotal);
}
}
}
solutions/ex06.java
/*
* Exercise 6: Average of fixed-deposit amounts (for-each preview).
* Run: javac ex06.java && java Ex06
*/
class Ex06 {
public static void main(String[] args) {
int[] deposits = {15000, 22000, 18500, 9000, 12500};
int total = 0;
for (int deposit : deposits) {
total += deposit;
}
System.out.println("Total: " + total);
System.out.println("Average: " + (total / deposits.length));
}
}
solutions/ex07.java
/*
* Exercise 7: Skip invalid entries, stop at a sentinel (break + continue).
* Run: javac ex07.java && java Ex07
*/
class Ex07 {
public static void main(String[] args) {
int[] cheques = {4000, -1, 7000, 0, 9500, -999, 3000};
int total = 0;
for (int cheque : cheques) {
if (cheque == -999) {
System.out.println("End of batch.");
break;
}
if (cheque <= 0) {
continue;
}
total += cheque;
System.out.println("Added " + cheque + ", total so far: " + total);
}
System.out.println("Final total: " + total);
}
}
solutions/ex08.java
/*
* Exercise 8: ATM menu with 3 PIN attempts (the capstone).
* Run: javac ex08.java && java Ex08
* (reads from standard input, e.g.
* printf "0000\n1111\n7733\n1\n2\n2000\n3\n1500\n4\n" | java Ex08)
*/
import java.util.Scanner;
class Ex08 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final String correctPin = "7733";
int attemptsLeft = 3;
boolean unlocked = false;
while (attemptsLeft > 0 && !unlocked) {
System.out.print("Enter 4-digit PIN: ");
String typed = scanner.nextLine();
if (typed.equals(correctPin)) {
unlocked = true;
System.out.println("PIN correct.");
} else {
attemptsLeft--;
if (attemptsLeft > 0) {
System.out.println("Wrong PIN. Attempts left: " + attemptsLeft);
} else {
System.out.println("Wrong PIN. Card blocked.");
}
}
}
if (unlocked) {
double balance = 8000.0;
boolean running = true;
while (running) {
System.out.println();
System.out.println("1. Check balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
int choice = Integer.parseInt(scanner.nextLine());
switch (choice) {
case 1:
System.out.println("Balance: Rs " + balance);
break;
case 2:
System.out.print("Deposit amount: Rs ");
double depositAmount = Double.parseDouble(scanner.nextLine());
if (depositAmount <= 0) {
System.out.println("Deposit must be positive. Ignored.");
} else {
balance += depositAmount;
System.out.println("Deposited Rs " + depositAmount + ". New balance: Rs " + balance);
}
break;
case 3:
System.out.print("Withdraw amount: Rs ");
double withdrawAmount = Double.parseDouble(scanner.nextLine());
if (withdrawAmount <= 0) {
System.out.println("Withdrawal must be positive. Ignored.");
} else if (withdrawAmount > balance) {
System.out.println("Insufficient balance. Current balance: Rs " + balance);
} else {
balance -= withdrawAmount;
System.out.println("Withdrew Rs " + withdrawAmount + ". New balance: Rs " + balance);
}
break;
case 4:
System.out.println("Goodbye.");
running = false; // break alone would only exit the switch, not this while
break;
default:
System.out.println("Invalid option, try again.");
}
}
}
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
if (x = 5) instead of if (x == 5) |
= is assignment, == is comparison — Java (unlike some languages) does catch most of these at compile time if x isn't boolean, but mixing them up still causes confusing errors |
Always == to compare, = to assign |
Forgetting break in a classic switch |
Execution falls through into the next case, running code you didn't intend | Put break at the end of every case (or use an arrow switch, which never falls through) |
Thinking break inside a switch exits an outer loop too |
break only exits the nearest enclosing switch or loop — a switch inside a loop swallows the break |
Use a boolean flag checked in the loop's condition, as Section 8 does |
Using a while (true) loop with no break anywhere |
The program never stops | Always have a reachable break or a condition that can become false |
Expecting for-each to change the array or expose the index |
The loop variable is a copy, and there is no index variable | Use a counting for loop when you need either |
Confusing &&/` |
` short-circuiting order | |
Mixing int and double division |
9500 / 1000 is integer division (9), even if the result is later stored in a double |
Make at least one operand a double (e.g. 9500.0 / 1000) if you want a fractional answer |
Quick recap
if/else/else-if pick a path; nestifs only when a question depends on a previous answer;?:is for picking one short value, not for side effects.- A classic
switchneedsbreakon every case or it falls through; an arrowswitchis an expression, never falls through, and is the right choice when every branch just produces a value. whilerepeats while a condition holds, checked before each pass — perfect for "retry until correct or out of attempts."forpacks init/condition/update into one line — best when you know how many times to repeat, including nested loops for grid-shaped work.for-eachreads every item in order with no index and no write-back; a countingforloop is still needed when you need either.breakleaves a loop completely;continueskips to the next pass; abreakinside aswitchinside a loop only exits theswitch— use a flag to end the loop itself.- The ATM menu capstone is nothing but these pieces stacked: a retry
whilefor the PIN, then a flag-drivenwhile+ classicswitchfor the menu.
Checklist
- I can write an else-if ladder and explain when nesting is clearer than a ladder.
- I can write a classic
switchwith correctbreaks, and explain fall-through. - I can write an arrow
switchexpression withyield, and choose between it and a classicswitch. - I can write a
whileloop that retries until success or a fixed number of attempts. - I can write nested
forloops for grid-shaped output. - I can write a
for-eachloop and know its two limits (no index, no write-back). - I can use
breakandcontinuecorrectly, and explain whybreakin aswitchinside a loop does not exit the loop. - I can build and run the ATM menu with 3 PIN attempts end to end.