---
title: "Operators, control flow, and methods"
chapter: "02"
---

# Operators, control flow, and methods

Control flow decides which statements execute and how often.

## Operators and precedence

Parenthesize when meaning is not immediate. `&&` and `||` short-circuit, so the
right side may not run. `&` and `|` on booleans evaluate both sides.

Integer division truncates: `7 / 2` is `3`. A compound assignment includes an
implicit cast, so `byte b = 1; b += 1;` compiles while `b = b + 1;` does not
without a cast.

## Conditions and loops

Use `if` for boolean branches. Modern `switch` can be an expression and must
produce a value on every path. Pattern matching can combine type testing and
binding. Use `for` when iteration shape is explicit and enhanced `for` when
walking elements. Use `while` for condition-driven repetition.

`break` exits a loop or switch. `continue` moves to the next loop iteration.
Labels exist but often signal deeply tangled control flow.

## Methods

A method signature includes its name and parameter types, not its return type.
Overloading selects a method at compile time from argument types. Overriding
selects instance behavior at runtime from the real object.

Java passes arguments **by value**. Passing an object copies the reference
value. A method can mutate the referenced object, but assigning its local
parameter to a new object does not change the caller's variable.

Varargs are arrays at runtime and must be the final parameter. Avoid ambiguous
overloads involving varargs, boxing, and widening.

## Recursion

Every recursive call consumes stack space. Define a base case and consider an
iterative solution for large depth; Java does not guarantee tail-call
optimization.

## Feynman check

Overloading is choosing one doorway before entering. Overriding is entering a
common doorway and letting the real object's room decide what happens.
