Language Fundamentals
Control Flow
Conditionals, loops, and switches steer execution. Modern Java strongly favors the arrow-form
switch — no fallthrough, and usable as an expression — plus the for-each loop for anything iterable.- Blocks define variable scope; you cannot redeclare a name in a nested block
- Classic
switchfalls through unless youbreak— arrowcase ->never does switchcan be an expression yielding a value (Java 14+)- Prefer for-each over indexed loops when you don't need the index (EJ 58)
- Labeled
break/continueescape nested loops without flags or goto
while (balance < goal) { balance += payment; } // test first
do { input = readInput(); } while (!isValid(input)); // body at least once
for (int i = 1; i <= 10; i++) { sum += i; } // counter idiom
for (String name : names) { greet(name); } // for-each: any array or Iterableswitch — old and new
int numLetters = switch (seasonName) {
case "SPRING", "SUMMER", "WINTER" -> 6;
case "FALL" -> 4;
default -> throw new IllegalArgumentException(seasonName);
};The arrow form has no fallthrough and each branch is a single expression or block (blocks produce a value with yield). When switching over an enum or sealed type and covering all cases, no default is needed — the compiler checks exhaustiveness, a major safety win. Pattern-matching switch extends this further; see Switch Expressions Pattern Matching.
search:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == target) {
found = true;
break search; // exits BOTH loops
}
}
}