Beginner⏱️ 8 min📘 Topic 5 of 22

🔀 Java Control Flow — if/else, switch, for, while Loops

Master Java control flow — if/else, switch (classic + switch expressions), for, enhanced for-each, while, do-while, break, continue and labeled loops with examples.

Control flow decides which code runs.

🟦 if / else if / else

if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else grade = 'F';

🟩 switch — classic and expression form

// Classic (needs break)
switch (day) {
  case 1: name = "Mon"; break;
  default: name = "?";
}

// Switch EXPRESSION (Java 14+) — no break, returns a value
String name = switch (day) {
  case 1, 7 -> "Weekend-ish";
  case 2, 3, 4, 5, 6 -> "Weekday";
  default -> "?";
};

🔁 Loops

  • for — counted: for (int i = 0; i < n; i++)
  • for-each — iterate collections: for (String s : list)
  • while — condition first
  • do-while — runs body at least once

🛑 break, continue, labels

break exits the loop; continue skips to the next iteration. Labeled breaks exit outer loops: outer: for(...) { for(...) { break outer; } }.

💡 The modern switch expression is exhaustive and arrow-based — no fall-through bugs. Prefer it for value assignment.

💻 Code Examples

Enhanced for-each

int[] nums = {10, 20, 30};
int sum = 0;
for (int n : nums) sum += n;
System.out.println(sum);
Output:
60

Switch expression with yield

int day = 3;
String type = switch (day) {
  case 6, 7 -> "Weekend";
  default -> {
    yield "Weekday";
  }
};
System.out.println(type);
Output:
Weekday

Labeled break

outer:
for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
    if (i + j == 3) break outer;
    System.out.print(i + "" + j + " ");
  }
}
Output:
00 01 02 10 11

⚠️ Common Mistakes

  • Forgetting break in a classic switch — execution falls through to the next case.
  • Using = instead of == in an if condition — Java rejects it for non-booleans, but `if (flag = true)` compiles and is a bug.
  • Modifying a collection inside a for-each loop — throws ConcurrentModificationException; use an Iterator or removeIf.
  • Off-by-one errors with `<=` vs `<` in for loops.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What's the difference between while and do-while?Beginner
while checks the condition before the body (may run zero times). do-while checks after (always runs at least once).
Q2.What's the difference between a switch statement and a switch expression?Intermediate
A switch statement executes code and uses break to avoid fall-through. A switch expression (Java 14+) returns a value using arrow syntax (or yield), is exhaustive, and has no fall-through — safer for assignments.
Q3.Why does modifying a list inside a for-each throw an exception?Intermediate
The enhanced for-each uses an Iterator internally. Structurally modifying the collection (add/remove) invalidates the iterator's modCount check, throwing ConcurrentModificationException. Use Iterator.remove() or Collection.removeIf().
Q4.What does a labeled break do?Beginner
It breaks out of an outer loop identified by a label, not just the innermost loop. Useful for exiting nested loops cleanly.

🧠 Quick Summary

  • if/else for ranges; switch for value matching.
  • Switch expressions (Java 14+) return values, no fall-through.
  • for (counted), for-each (collections), while, do-while.
  • break exits, continue skips; labels target outer loops.
  • Don't modify a collection during a for-each — use removeIf/Iterator.