Skip to content

Chapter 03Part I · Foundations

Operators and Control Flow

4 min read6 runnable examples

In this chapter: how Java evaluates expressions, the operators that surprise people most, and the biggest control-flow story in modern Java: how switch grew from a fall-through statement into a pattern-matching expression.

Key points

  • Expressions evaluate left to right; precedence decides grouping. i++ + ++i with i = 5 is 12.
  • Integer / truncates toward zero and % takes the sign of the dividend: -7 % 3 is -1. Use Math.floorMod (Java 8) for a remainder that's never negative.
  • && and || short-circuit; & and | always evaluate both sides. >> keeps the sign, >>> fills with zeros.
  • switch grew up: strings (Java 7), arrows and switch expressions with yield (Java 14), type patterns, guards and case 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. instanceof gained 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 * c groups as a + (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++ + ++i is undefined behavior there. Java defines it.
code/ch03/Precedence.java
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);
    }
}
r = 12, i = 7
x = 200
42 42 42

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

code/ch03/DivMod.java
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

code/ch03/ShortCircuit.java
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));
    }
}
&& (short-circuit):
  evaluated left
&  (always both):
  evaluated left
  evaluated right
safe: false

&& 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

code/ch03/SwitchJava7.java
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"));
    }
}
JUN 30
FEB 31   <- fall-through bug
JAN 31

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:

code/ch03/SwitchExpression.java
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));
    }
}
JUN 30
FEB 28
FEB 29 (leap)
JAN 31
  1. Arrow labels (->) never fall through. Each case runs its right side and stops.
  2. Several labels share one case, separated by commas.
  3. switch can be an expression that produces a value. Inside a block, yield hands 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:

code/ch03/PatternSwitch.java
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));
        }
    }
}
an int 42
a negative int -7
a string of length 4
an int array of 3
something else: Double
nothing
  • case Integer i tests the type and binds i in one step, so no cast is needed.
  • when adds a guard. Cases are tried top to bottom, so the guarded case must come before the general Integer case. The compiler rejects the opposite order as unreachable.
  • case null handles null explicitly. Without it, a switch on null still throws NullPointerException, as it always did.
  • With a sealed hierarchy (Chapter 19), the compiler can prove a switch covers every subtype, and you can drop default entirely.

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.

Read the complete chapter →

Summary

  • Operands are evaluated left to right; precedence only decides grouping. Use parentheses for readers.
  • / truncates toward zero, % follows the dividend's sign, and Math.floorMod gives a non-negative remainder.
  • &&/|| short-circuit. >>> is the zero-filling shift. Shift distances wrap.
  • switch evolved 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.