Language Fundamentals
Operators & Expressions
Java's operators mostly follow C conventions — with well-defined evaluation order, integer division that truncates toward zero, short-circuit logical operators, and a distinct unsigned right shift.
- Integer
/truncates toward zero;%can be negative — useMath.floorModfor cyclic indexing &&and||short-circuit;&and|always evaluate both sides>>keeps the sign bit (arithmetic shift);>>>fills with zeros (logical shift)- Operands are evaluated left to right, and mixed-type arithmetic promotes to the wider type
- The conditional operator
cond ? a : bis an expression — use it for simple selections
Arithmetic (+ - * / %), comparison (== != < <= > >=), logical (&& || !), bitwise (& | ^ ~), shifts (<< >> >>>), assignment and compound assignment (+= etc.), increment/decrement (++ --), and the ternary conditional. Precedence follows C; when in doubt, parenthesize — the reader benefits even when the compiler doesn't need it.
System.out.println(15 / 2); // 7
System.out.println(15 % 2); // 1
System.out.println(-7 % 3); // -1 (sign follows dividend)
System.out.println(Math.floorMod(-7, 3)); // 2
System.out.println(1.0 / 0); // Infinity (no exception!)NaN (not-a-number) results from 0.0/0 or Math.sqrt(-1). No `NaN` is equal to anything, including itself — test with Double.isNaN(x), never x == Double.NaN.
Short-circuit evaluation
&& and || evaluate the right operand only when needed — the idiomatic guard if (list != null && !list.isEmpty()) depends on it. The single-character forms & and | on booleans always evaluate both sides; on integers they are bitwise operations.
Bit manipulation
int flags = 0b0110;
boolean third = (flags & 0b0100) != 0; // test a bit
flags |= 0b0001; // set a bit
flags &= ~0b0010; // clear a bit
System.out.println(-8 >> 1); // -4 (sign-extends)
System.out.println(-8 >>> 1); // 2147483644 (zero-fills)