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 switch falls through unless you break — arrow case -> never does
  • switch can 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/continue escape nested loops without flags or goto
The loop family
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 Iterable

switch — old and new

Arrow switch as an expression (Java 14+)
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.

Labeled break
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
        }
    }
}
Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 3.8 — Control Flow
  • Learning Java (6th ed.)Ch. 4 — The Java Language (Statements)
  • Effective Java (3rd ed.)Items 57, 58