determines the order in which statements execute. Java provides conditionals (, ), loops (, , ), and branching statements (, , ) — plus modern enhancements like switch expressions.
ifswitchforwhiledo-whilebreakcontinuereturnif (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "F";
}
// ternary — concise if/else for a value
String status = (age >= 18) ? "adult" : "minor";
switch (day) {
case 1: name = "Mon"; break; // ⚠️ break needed — else it FALLS THROUGH
case 2: name = "Tue"; break;
default: name = "Unknown";
}
The classic switch requires break after each case — forgetting it causes fall-through (execution continues into the next case), a notorious bug source.
// arrow syntax: no fall-through, returns a value, more concise
String name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 6, 7 -> "Weekend"; // multiple labels
default -> "Unknown";
};
The modern switch expression eliminates fall-through, can return a value, and is cleaner — preferred in new code.
// for — known iteration count
for (int i = 0; i < 10; i++) { ... }
// enhanced for-each — iterate a collection/array
for (String item : items) { ... }
// while — condition checked BEFORE each iteration
while (condition) { ... }
// do-while — body runs at least ONCE (condition checked after)
do { ... } while (condition);
for (int i = 0; i < 10; i++) {
if (i == 5) break; // exit the loop entirely
if (i % 2 == 0) continue; // skip to the next iteration
}
return result; // exit the method
// labeled break — exit nested loops
outer:
for (...) {
for (...) {
if (found) break outer; // breaks BOTH loops
}
}
break exits a loop, continue skips to the next iteration, return exits the method, and labeled breaks can exit nested loops at once.
Control flow is the basic mechanism for expressing logic and decisions in any program — every non-trivial method uses it.
Understanding the constructs and their nuances is essential: the switch fall-through gotcha (and the safer modern switch expression), the difference between while and do-while (run-at-least-once), the for-each for clean collection iteration, and the branching statements (including labeled breaks for nested loops).
Mastering these — and preferring the modern, less error-prone forms (switch expressions, for-each) — is fundamental to writing correct, readable Java logic and avoiding common control-flow bugs.