Control Flow in Java
Control flow statements decide which code runs and how often: if and switch choose between paths, loops repeat, and break, continue and return jump. Java's switch in particular has changed more than any other statement, from C-style fall-through to expressions and pattern matching. This page explains each construct, runs examples of every form, and shows the loop and branching mistakes that compile without complaint.
Contents
The building blocks
A Java method runs its statements top to bottom unless a control flow statement changes the order. There are three groups:
| Group | Constructs | Use for |
|---|---|---|
| Decisions | ifelse? :switch | Choosing one path out of several |
| Loops | forforwhiledowhile | Repeating work |
| Jumps | breakcontinuereturnyieldthrow | Leaving a loop, switch or method early |
Two rules shape all of them. Conditions must be booleanif (count)intif (x = 5)ifswitch
if, else and the ternary operator
The program grades four scores, one per branch, picks a stock label with nested ternaries, shows why &&
public class IfAndConditions {
static String grade(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
static int checks;
static boolean expensive(boolean answer) {
checks++;
return answer;
}
public static void main(String[] args) {
for (int s : new int[] {95, 85, 72, 40}) {
System.out.print(s + "=" + grade(s) + " ");
}
System.out.println();
// The ternary operator is an expression: it produces a value
int stock = 3;
String label = stock == 0 ? "sold out" : stock < 5 ? "few left" : "in stock";
System.out.println("stock 3: " + label);
// && and || skip the right side when the left side decides the result
String name = null;
if (name != null && name.length() > 3) {
System.out.println("long name");
} else {
System.out.println("null-safe check passed without NullPointerException");
}
checks = 0;
boolean result = expensive(true) || expensive(false);
System.out.println("true || x evaluated " + checks + " operand(s), result " + result);
// A dangling else belongs to the nearest if, whatever the indentation says
int a = 5;
int b = -1;
String outcome = "unset";
if (a > 0)
if (b > 0)
outcome = "both positive";
else
outcome = "a is not positive?";
System.out.println("a=5, b=-1 gives: " + outcome);
}
}
Output:
95=A 85=B 72=C 40=F
stock 3: few left
null-safe check passed without NullPointerException
true || x evaluated 1 operand(s), result true
a=5, b=-1 gives: a is not positive?
- An
/if chain tests conditions in order and runs the first branch that matches, so the order matters: 95 is also at least 80, but theelse if test comes first.>= 90 - The ternary
is an expression, so it can be assigned or returned directly. Nesting works, as with the stock label, but more than two levels is hard to read; usecondition ? a : b or a switch expression instead.if and&& evaluate the right side only if needed.|| never callsname != null && name.length() > 3 onlength() , andnull evaluated just 1 operand. The singletrue || x and& always evaluate both sides (see|bitwise operators ).- The last example printed "a is not positive?" although a is 5. An
always belongs to the nearestelse without one, hereif , whatever the indentation suggests. This "dangling else" is why style guides require braces on every branch.if (b > 0)
switch: from statement to pattern matching
switchyieldnull
import java.time.DayOfWeek;
public class SwitchForms {
// 1. The classic switch statement: cases fall through without break
static int daysOld(int month) {
int days;
switch (month) {
case 2:
days = 28;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
}
return days;
}
// 2. A switch expression (Java 14): arrows, several labels, a value, no fall-through
static int days(int month) {
return switch (month) {
case 2 -> 28;
case 4, 6, 9, 11 -> 30;
default -> 31;
};
}
// 3. Over an enum, every constant handled: no default needed, and yield for blocks
static String kind(DayOfWeek day) {
return switch (day) {
case SATURDAY, SUNDAY -> "weekend";
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
String note = day == DayOfWeek.FRIDAY ? " (almost weekend)" : "";
yield "weekday" + note;
}
};
}
// 4. Pattern matching (Java 21): types, guards and null
static String describe(Object o) {
return switch (o) {
case null -> "nothing";
case Integer i when i > 1000 -> "big number";
case Integer i -> "number " + i;
case String s -> "text of length " + s.length();
default -> "other: " + o.getClass().getSimpleName();
};
}
// A forgotten break falls into the next case (-Xlint:fallthrough warns about it)
@SuppressWarnings("fallthrough")
static String fallThrough(int level) {
StringBuilder sb = new StringBuilder();
switch (level) {
case 1:
sb.append("one ");
case 2:
sb.append("two ");
default:
sb.append("default");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println("Feb " + daysOld(2) + "/" + days(2) + ", Apr " + daysOld(4) + "/"
+ days(4) + ", Jul " + daysOld(7) + "/" + days(7));
System.out.println("level 1 without break: " + fallThrough(1));
System.out.println("FRIDAY: " + kind(DayOfWeek.FRIDAY)
+ ", SUNDAY: " + kind(DayOfWeek.SUNDAY));
System.out.println(describe(5000) + ", " + describe(7) + ", " + describe("hey") + ", "
+ describe(null) + ", " + describe(2.5));
// Switch on a String is case-sensitive, and an old-style switch on null throws
String command = null;
try {
switch (command) {
case "start" -> System.out.println("starting");
default -> System.out.println("unknown");
}
} catch (NullPointerException e) {
System.out.println("switch on a null String without case null: NullPointerException");
}
}
}
Output:
Feb 28/28, Apr 30/30, Jul 31/31
level 1 without break: one two default
FRIDAY: weekday (almost weekend), SUNDAY: weekend
big number, number 7, text of length 3, nothing, other: Double
switch on a null String without case null: NullPointerException
- In the classic form, execution starts at the matching
and continues into the next ones until acase . Several empty cases in a row (break ) share code this way. Forgetting acase 4: case 6: ... does the same thing by accident: level 1 printed "one two default". javac warns about it withbreak .-Xlint:fallthrough - The arrow form (
) never falls through and can list several labels in one case. As an expression it must produce a value for every input, so acase 4, 6, 9, 11 -> 30 is required for andefault .int - Over an enum, a switch expression that handles every constant needs no
. If a constant is added to the enum later, the switch stops compiling instead of silently doing nothing. A case whose result needs several statements uses a block withdefault .yield - Pattern matching (Java 21) switches on the type:
matches and casts in one step,case Integer i adds a condition, and the more specificwhen case must come first.when i > 1000 handlescase null explicitly; seenullpattern matching for switch . - A switch without
throwscase null when givenNullPointerException , in every form. String cases are compared withnull , so they are case-sensitive.equals
| Java | Feature |
|---|---|
| 5 | Enums in case |
| 7 | Strings in case |
| 14 | Switch expressions, arrow labels, several labels per case, yield |
| 21 | Type patterns, whencase null |
For more, see
The four loops, break, continue and labels
The program uses each loop where it fits best. The while
public class Loops {
public static void main(String[] args) {
// for: when you know how many times
for (int i = 1; i <= 3; i++) {
System.out.print("for " + i + " ");
}
System.out.println();
// while: test first, may run zero times
int n = 27;
int steps = 0;
while (n != 1) { // Collatz sequence
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
System.out.println("27 reaches 1 after " + steps + " steps");
// do-while: body runs at least once
int tries = 0;
do {
tries++;
} while (tries < 0);
System.out.println("do-while ran " + tries + " time; its condition was false");
// break and continue
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
if (i > 7) {
break; // stop the loop entirely
}
System.out.print(i + " ");
}
System.out.println();
// A labeled break leaves both loops at once
int[][] grid = {
{1, 2, 3},
{4, 42, 6},
{7, 8, 9}
};
search:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == 42) {
System.out.println("found 42 at row " + r + ", column " + c);
break search;
}
}
}
}
}
Output:
for 1 for 2 for 3
27 reaches 1 after 111 steps
do-while ran 1 time; its condition was false
1 2 4 5 7
found 42 at row 1, column 1
fits a known number of iterations: initialization, condition and update are in one line.for tests first and may run zero times. Starting from 27, the Collatz rule (halve even numbers, otherwise triple and add one) took 111 steps to reach 1.while -do tests after the body, so it ran once even though its condition was false from the start. It suits "do something, then check whether to repeat", such as prompting until the input is valid.while skipped 3 and 6;continue ended the loop at 8, so 9 and 10 were never reached.break- A plain
leaves only the innermost loop.break left both loops as soon as 42 was found. Labels are rarely needed, and often a separate method withbreak search reads better.return
| Loop | Use when |
|---|---|
for-each: for (T x : items) | Visiting every element of an array or Iterable |
for (int i = 0; i < n; i++) | You need the index, or to step differently, or to iterate two arrays together |
while (condition) | The number of iterations is not known in advance |
do { } while (condition) | The body must run at least once |
| A stream | Filtering, transforming and collecting; see |
Loop traps that compile without warnings
Each loop in this program compiles cleanly and is wrong in a way that is easy to miss in review. Where a loop would run forever, the program adds a safety limit so it can show what happened.
import java.util.List;
public class LoopTraps {
public static void main(String[] args) {
// 1. A floating-point counter may never equal its end value
int iterations = 0;
for (double x = 0.0; x != 1.0 && iterations < 20; x += 0.1) {
iterations++;
}
System.out.println("x != 1.0 loop stopped by the safety limit after " + iterations);
int counted = 0;
for (int tenths = 0; tenths < 10; tenths++) {
counted++; // count in integers, compute x = tenths / 10.0
}
System.out.println("integer counter ran " + counted + " times");
// 2. An int counter cannot exceed Integer.MAX_VALUE, so "<=" MAX never becomes false
long laps = 0;
for (int i = Integer.MAX_VALUE - 2; i <= Integer.MAX_VALUE; i++) {
if (++laps > 5) {
System.out.println("i wrapped around to " + i + "; stopped after " + laps);
break;
}
}
// 3. Off by one: < length visits every index, <= length goes one too far
int[] data = {10, 20, 30};
try {
for (int i = 0; i <= data.length; i++) {
System.out.print(data[i] + " ");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("<- then " + e.getMessage());
}
// 4. Labeled continue: skip to the next row as soon as a row is invalid
List<int[]> rows = List.of(new int[] {1, 2}, new int[] {3, -1, 5}, new int[] {6});
int sum = 0;
rows:
for (int[] row : rows) {
for (int v : row) {
if (v < 0) {
continue rows; // ignore the whole row
}
}
for (int v : row) {
sum += v;
}
}
System.out.println("sum of rows without negatives: " + sum);
// 5. for-each over a null collection throws NullPointerException
List<String> missing = null;
try {
for (String s : missing) {
System.out.println(s);
}
} catch (NullPointerException e) {
System.out.println("for-each over null: NullPointerException");
}
}
}
Output:
x != 1.0 loop stopped by the safety limit after 20
integer counter ran 10 times
i wrapped around to -2147483646; stopped after 6
10 20 30 <- then Index 3 out of bounds for length 3
sum of rows without negatives: 9
for-each over null: NullPointerException
- Adding 0.1 ten times does not give exactly 1.0 (see
data types ), so stayed true and only the safety limit stopped the loop. Count with an integer and compute the fraction from it.x != 1.0 - Every
isint , so that condition can never become false: after<= Integer.MAX_VALUE ,MAX_VALUE wrapped around to a negative number and the loop would have continued forever. Use ai++ counter or along bound below the maximum.< - Indexes run from 0 to
. Withlength - 1 , the loop printed all three values and then failed on index 3. Prefer for-each when the index is not needed; it cannot get the bounds wrong.<= abandoned a row as soon as it contained a negative number and moved to the next one, so only {1, 2} and {6} were added: 9.continue rows- A for-each loop over
throwsnull , because it callsNullPointerException . Methods that return collections should return an empty one, neveriterator() .null
Removing elements from a collection while looping over it with for-each is another classic trap; see
Summary
| Situation | Use |
|---|---|
| Two or three conditions | ifelse if |
| Choosing between two values | The ternary operator |
| One value compared with many constants | A switch expression with arrows |
| Different handling per type | A pattern matching switch, ideally over a sealed type |
| Every element of a collection | for-each, or a stream for transformations |
| Repeat until a condition changes | whiledowhile |
| Leaving nested loops | Extract a method and returnbreak |