Java basics: operators, branching and why the machine doesn't compute like paper
Why machine arithmetic overflows, drops the fraction in division and makes `==` compare identity; how to choose between if, switch and polymorphism; how to review arithmetic and branching in AI-written code. With bits, two's complement, switch expressions and pattern matching.
On this page
1. The problem
A "remember me for 30 days" session computes its expiry as 30 * 24 * 60 * 60 * 1000. The result is -1,702,967,296 ms: every session expires the moment it's created. Tests only tried 1 day (86,400,000 ms, which fits in an int), so they stayed green.
2. Key idea
Operators work on fixed-width types and on references. Results diverge from math in three places.
| Divergence | In Java | Elsewhere |
|---|---|---|
| Overflow | int is two's complement; overflow wraps, nothing is thrown |
Go and C# wrap too; Python has no limit |
| Integer division, remainder | -7 / 2 == -3, -7 % 2 == -1 |
Python floors: -7 % 2 == 1 |
| Identity vs value | == on objects compares addresses; Integer only caches -128..127 |
JavaScript {} === {} is false; SQL NULL = NULL isn't true |
Also: every comparison with NaN is false, so score < 0 || score > 10 lets NaN through. Write the positive form and negate the whole thing: !(score >= 0 && score <= 10).
2.1 How to branch?
| Approach | Use when | Don't use when |
|---|---|---|
if / else if, guard clauses |
ranges, compound conditions | comparing one variable against many constants |
| Switch expression (Java 14+) | closed value sets, want the compiler to check coverage | range conditions like score >= 8 |
| Pattern switch (Java 21) | branching on type, with when |
open type sets other modules extend |
Polymorphism, Map<Key, Handler> |
branches by "type" that keep growing | 2–3 simple, stable branches |
A switch expression over an enum without default: adding a constant and forgetting to handle it is a compile error right where it matters.
3. In Java
long ttlMs = 30L * 24 * 60 * 60 * 1000; // 2,592,000,000: L suffix on the first operand
int total = Math.addExact(a, b); // throws ArithmeticException on overflow
int shard = Math.floorMod(key.hashCode(), 10); // always 0..9, even for negative hashes
boolean same = Objects.equals(ownerId, userId); // Long, Integer, String: never ==
int x = 5;
x = x++; // x is still 5: x++ returns 5, then it's assigned back
short s = 1;
s += 5; // compiles: += casts implicitly
// s = s + 5; // compile error: s + 5 is an int
String fee = switch (type) { // enum TxType, no default
case TOPUP -> "0%";
case TRANSFER -> "0.1%";
case WITHDRAW -> "0.5%";
};Switching on long, double or boolean still isn't in a final release; primitive patterns are still in preview as of JDK 27. Other languages: C# has checked blocks; Node.js uses BigInt beyond 2^53.
Bitwise operators and ~5
For each pair of bits in the same position: & gives 1 when both are 1, | when at least one is, ^ when they differ. With 5 = 0101, 3 = 0011: 5 & 3 = 1, 5 | 3 = 7, 5 ^ 3 = 6, 5 << 2 = 20, 5 >> 2 = 1.
~5 == -6 because an int has 32 bits: it flips the 28 leading zeros too, giving a negative number; in general ~x == -x - 1. You meet these in permission bitmasks, feature flags, hashing (HashMap uses h ^ (h >>> 16)) and power-of-two checks: (n & (n - 1)) == 0.
4. Working with AI
Give the AI: boundary-value tests (0, -1, MIN_VALUE, MAX_VALUE, 127 and 128, NaN, null), turning if chains into switch expressions.
Check in AI-written code:
- Multiplications and running sums that can exceed 2.1 billion use
longorMath.*Exact. - No
Math.abs(x) % nused as an index. - No
==betweenInteger,LongorString; enable Error Prone'sBoxedPrimitiveEquality. - Switches over the service's own enums have no
default. - Floating-point range checks catch
NaN.
5. Exercises
Exercise 1: A shard picker
The AI says: "Always a non-negative index; tested with 1 million UUIDs." The system has 10 shards.
static int shardFor(String key, int shards) {
return Math.abs(key.hashCode()) % shards;
}Find an input that breaks it, and fix it without moving any existing key.
Solution to Exercise 1
Math.abs(Integer.MIN_VALUE) returns MIN_VALUE itself. The string "polygenelubricants" has a hashCode() of exactly Integer.MIN_VALUE, so the function returns -8 and shards[-8] throws ArrayIndexOutOfBoundsException. A million UUIDs almost surely never hit it (probability 1/2^32).
Don't switch wholesale to Math.floorMod: for negative hashes the formulas differ (h = -13: abs gives 3, floorMod gives 7), so every negative-hash key would move shards. Block only the value that could never be stored:
int h = key.hashCode();
if (h == Integer.MIN_VALUE) return 0; // used to throw, so no data lives here
return Math.abs(h) % shards;Exercise 2: 403s after a refactor
After a deploy, 403s on GET /orders/{id} rise from 0.1% to 38%, matching the share of mobile requests. Logs: ownerId=10452 currentUserId=10452 allowed=false. The diff changed a DTO's long ownerId to Long ownerId. The check is order.ownerId() == principal.userId(); the web principal returns long, mobile returns Long. Diagnose, the 15-minute action, the root fix.
Solution to Exercise 2
- Diagnosis: web compares
Longwithlong; Java unboxes and compares values, so it works. Mobile comparesLongwithLong:==compares two objects, equal only for ids in -128..127. Tests used ids 1 to 50, so they passed. - 15 minutes: roll back, or hotfix with
Objects.equals(...). This bug wrongly denies rather than wrongly allows, so no data leaked. - Root fix: make
BoxedPrimitiveEqualitya build error; keep ids aslongin the domain; authorization tests use ids above 127.
Summary
intoverflow wraps silently: uselongorMath.*Exact.%takes the dividend's sign; for non-negative indexes useMath.floorMod.==on objects compares identity; compare values withequals.- Every comparison with
NaNisfalse. - Closed sets: a switch expression without
default; ever-growing "types": polymorphism.
Read more: Loops and methods.
For further reading, Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition) is a good book.
Practice interview questions on this topic
- What are the common Java operator traps: integer division, %, a++ vs ++a, && vs &, bitwise operators?
- What is the difference between implicit and explicit casting? Why does s = s + 1 fail but s += 1 compile?
- What problem do sealed interfaces and pattern matching for switch (Java 21) solve?
- When do you choose a sealed interface with records over an enum? How do you refactor an ever-growing if/else on "type"?
- What is a race condition? How do you fix count++ on a shared variable?
- What are wrapper classes and autoboxing? Why is a == b false for Integer a = 128, b = 128?
Comments
Community rules