Chapter 03Part I · Foundations
Operators and Control Flow
In this chapter: how Java evaluates expressions, the operators that surprise people most, and the biggest control-flow story in modern Java: how
switchgrew from a fall-through statement into a pattern-matching expression.
Key points
- Expressions evaluate left to right; precedence decides grouping.
i++ + ++iwithi = 5is12. - Integer
/truncates toward zero and%takes the sign of the dividend:-7 % 3is-1. UseMath.floorMod(Java 8) for a remainder that's never negative. &&and||short-circuit;&and|always evaluate both sides.>>keeps the sign,>>>fills with zeros.switchgrew up: strings (Java 7), arrows and switch expressions withyield(Java 14), type patterns, guards andcase null(Java 21).- No new arithmetic or logical operators arrived between Java 7 and 27; Java 8's
->and::are syntax for lambdas and method references.instanceofgained patterns (Java 16), which removed most casts.
How Java evaluates an expression
Two separate rules decide what an expression means:
- Precedence and associativity decide how operators group.
a + b * cgroups asa + (b * c). - Evaluation order decides when each operand is computed. In Java it's always left to right, and every operand is evaluated before the operator is applied. C and C++ leave this unspecified, which is why
i++ + ++iis undefined behavior there. Java defines it.
public class Precedence {
public static void main(String[] args) {
int i = 5;
int r = i++ + ++i; // 5 (then i = 6) + 7 (i becomes 7 first)
System.out.println("r = " + r + ", i = " + i);
// * / % bind tighter than +, left to right
int x = 10 * 20 + -30 * 2 / 4 % 3;
System.out.println("x = " + x);
int a, b, c;
a = b = c = 42; // assignment is right-associative
System.out.println(a + " " + b + " " + c);
}
}
Walk through i++ + ++i: the left operand i++ produces 5 and sets i to 6. The right operand ++i sets i to 7 and produces 7. The sum is 12. It's well-defined, but write it this way in real code and your reviewers will rightly reject it.
The classic rule
"Rule → Except the assignment, all binary operators have Left to Right associativity. Unary and ternary operators have Right to Left."
Still exactly right. It's why a = b = c = 42 works: it groups as a = (b = (c = 42)).
Division and remainder
public class DivMod {
public static void main(String[] args) {
System.out.println(" 7 / 2 = " + (7 / 2));
System.out.println("-7 / 2 = " + (-7 / 2)); // truncates toward zero
System.out.println(" 7 % 3 = " + (7 % 3));
// sign follows the dividend
System.out.println("-7 % 3 = " + (-7 % 3));
System.out.println(" 7 % -3 = " + (7 % -3));
// Java 8
System.out.println("floorMod(-7, 3) = " + Math.floorMod(-7, 3));
System.out.println("isOdd(-3) with % 2 == 1 ? " + (-3 % 2 == 1));
}
}
7 / 2 = 3
-7 / 2 = -3
7 % 3 = 1
-7 % 3 = -1
7 % -3 = 1
floorMod(-7, 3) = 2
isOdd(-3) with % 2 == 1 ? false
Integer division throws away the fraction, rounding toward zero, so -7 / 2 is -3, not -4. The remainder follows so that (a / b) * b + a % b == a always holds, which means % takes the sign of the left operand.
The odd-number bug
n % 2 == 1 is false for every negative odd number. Write n % 2 != 0. If you need a remainder that's never negative, such as when wrapping around a circular buffer, use Math.floorMod (Java 8).
Logical operators and short-circuiting
public class ShortCircuit {
static boolean check(String name, boolean result) {
System.out.println(" evaluated " + name);
return result;
}
public static void main(String[] args) {
System.out.println("&& (short-circuit):");
if (check("left", false) && check("right", true)) { }
System.out.println("& (always both):");
if (check("left", false) & check("right", true)) { }
String s = null;
System.out.println("safe: " + (s != null && s.length() > 3));
}
}
&& and || stop as soon as the result is known. That's what makes the guard s != null && s.length() > 3 safe. On boolean values, & and | are logical operators too, but they always evaluate both sides. Use them only when the right side has a side effect you need, which is rare.
The journey of switch
switch is the clearest example in Java of a feature being rebuilt in small, compatible steps.
flowchart LR
A["Java 1.0<br/>int, char, byte, short<br/>fall-through by default"] --> B["Java 5<br/>enums and wrappers"]
B --> C["Java 7<br/>String labels"]
C --> D["Java 14<br/>arrow labels,<br/>switch expressions, yield"]
D --> E["Java 21<br/>type patterns, guards,<br/>case null, exhaustiveness"]
Java 7: strings, and the fall-through problem
public class SwitchJava7 {
static int daysIn(String month) {
int days = 0;
switch (month) { // strings in switch: Java 7
case "APR":
case "JUN":
case "SEP":
case "NOV":
days = 30;
break;
case "FEB":
days = 28;
// forgot break: falls through!
default:
days = 31;
}
return days;
}
public static void main(String[] args) {
System.out.println("JUN " + daysIn("JUN"));
System.out.println("FEB " + daysIn("FEB") + " <- fall-through bug");
System.out.println("JAN " + daysIn("JAN"));
}
}
Java 7 let you switch on a String, which the compiler implements with hashCode() and equals(). But it kept C's oldest trap: without break, control falls through into the next case. The missing break after FEB is a real bug that compiles without a warning, unless you turn on -Xlint:fallthrough.
Java 14: switch expressions
Switch expressions (JEP 361) fixed three things at once:
public class SwitchExpression {
static int daysIn(String month, boolean leap) {
// Java 14: switch is an expression
return switch (month) {
// several labels, no fall-through
case "APR", "JUN", "SEP", "NOV" -> 30;
case "FEB" -> {
int d = leap ? 29 : 28;
yield d; // yield returns a value from a block
}
default -> 31;
};
}
public static void main(String[] args) {
System.out.println("JUN " + daysIn("JUN", false));
System.out.println("FEB " + daysIn("FEB", false));
System.out.println("FEB " + daysIn("FEB", true) + " (leap)");
System.out.println("JAN " + daysIn("JAN", false));
}
}
- Arrow labels (
->) never fall through. Each case runs its right side and stops. - Several labels share one case, separated by commas.
switchcan be an expression that produces a value. Inside a block,yieldhands the value back. A switch expression must cover every possible input, so you can't forget a case and silently get the default value of a variable.
Java 21: pattern matching for switch
The final step (JEP 441) lets a switch test the type of a value, bind it to a variable, and add a condition:
public class PatternSwitch {
static String describe(Object value) {
return switch (value) { // Java 21
case null -> "nothing";
// guard with 'when'
case Integer i when i < 0 -> "a negative int " + i;
case Integer i -> "an int " + i;
case String s -> "a string of length " + s.length();
case int[] arr -> "an int array of " + arr.length;
default -> "something else: "
+ value.getClass().getSimpleName();
};
}
public static void main(String[] args) {
Object[] samples =
{ 42, -7, "Java", new int[] {1, 2, 3}, 3.14, null };
for (Object o : samples) {
System.out.println(describe(o));
}
}
}
case Integer itests the type and bindsiin one step, so no cast is needed.whenadds a guard. Cases are tried top to bottom, so the guarded case must come before the generalIntegercase. The compiler rejects the opposite order as unreachable.case nullhandlesnullexplicitly. Without it, aswitchonnullstill throwsNullPointerException, as it always did.- With a sealed hierarchy (Chapter 19), the compiler can prove a
switchcovers every subtype, and you can dropdefaultentirely.
Migration tip
Convert old switch statements to the arrow form even when you don't need a value. Arrows remove fall-through entirely, and most IDEs can do it for you. Reach for type patterns wherever you see an if (x instanceof A) { A a = (A) x; … } else if … chain.
The journey at a glance
timeline
title Operators and control flow, Java 7 → 27
2011 : Java 7 : strings in switch
2014 : Java 8 : lambda arrow, Math.floorMod
2020 : Java 14 : switch expressions, arrow labels, yield
2021 : Java 16 : pattern matching for instanceof
2023 : Java 21 : pattern matching for switch, guards, case null
Go deeper in the complete edition
This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.
Summary
- Operands are evaluated left to right; precedence only decides grouping. Use parentheses for readers.
/truncates toward zero,%follows the dividend's sign, andMath.floorModgives a non-negative remainder.&&/||short-circuit.>>>is the zero-filling shift. Shift distances wrap.switchevolved from fall-through statements (Java 7 strings) to expressions (14) to pattern matching (21).
Next: Part II begins. Chapter 4 looks at what an object really is, where it lives, and what a reference variable holds.