Java Control Flow

Conditionals & Loops

Decision-making and iteration — if/else, the modern switch expression, and every loop form Java offers.

Java 21 ✓ Core Concepts 2 Topics
01

Conditionals & switch

Modern Java (14+) added the switch expression with arrow syntax — it returns a value, needs no break, and the compiler forces you to cover every case.

Java — if, ternary & switch expression
int age = 20;

// if / else if / else
if (age >= 18) System.out.println("adult");
else System.out.println("minor");

// Ternary — compact if/else expression
String status = age >= 18 ? "adult" : "minor";

// Modern switch expression (Java 14+) — returns a value, no break, no fall-through
int day = 3;
String name = switch (day) {
    case 1, 7 -> "weekend-ish";   // multiple labels per case
    case 2, 3, 4, 5, 6 -> "weekday";
    default -> "invalid";
};
The old switch statement with : and break still works and still falls through if you forget a break. The arrow form -> never falls through — prefer it in new code.
02

Loops in Java

Java — for, while, for-each
// classic for — index-based
for (int i = 0; i < 5; i++) System.out.println(i);   // 0 1 2 3 4

// while — condition checked first
int n = 3;
while (n > 0) { System.out.println(n); n--; }

// do-while — body runs at least once
do { System.out.println("runs once minimum"); } while (false);

// for-each — iterate any array or Iterable
int[] nums = {3, 7, 2, 9};
int max = nums[0];
for (int x : nums) {          // "for each x in nums"
    if (x > max) max = x;
}
System.out.println(max);          // 9

// break exits, continue skips to next iteration
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;    // skip 2
    if (i == 4) break;       // stop at 4
    System.out.println(i);      // 0 1 3
}
Use for-each when you just need the values and never touch the index — it's cleaner and avoids off-by-one bugs. Use the classic for when you need the index itself or must iterate backwards.

Quick Quiz

1. The modern switch expression (arrow form) …
2. Which loop always runs its body at least once?
3. continue does what?
4. for (int x : nums) is called a…
5. In the old switch statement, forgetting break causes…