DEV Community

aaannvv
aaannvv

Posted on Edited on

Five Java Traps That Eliminate 90% of Interview Candidates (And the Spec-Level Why)

These are not puzzle questions. Each one is code that compiles, runs, and hands you the wrong answer — and the wrong answer sounds right if you learned Java from tutorials instead of the spec. Here are five, with the JLS-level reasoning that separates candidates who derive from candidates who recite.

1. The odd check that misses negatives

boolean isOdd(int n) — return n % 2 == 1;

-3 % 2 evaluates to -1, not 1. In Java, the remainder operator takes the sign of the dividend. Every negative odd number returns false. The fix: n % 2 != 0, or the bit trick (n & 1) != 0.

The meta-skill: ask what the static type and sign of each operand is at each step. Derivation, not memorization.

2. The Integer cache cliff

Integer a = 127, b = 127; a == b is true. Integer x = 128, y = 128; x == y is false.

Integer.valueOf caches -128 to 127. Above the cache, each box is a fresh object. The production lesson: never use == on boxed types. The interview lesson: this is not trivia — it is a design consequence (autoboxing spec) that you should be able to derive from first principles.

3. finally overrides the return

int f() { try { return 1; } finally { return 2; } } — returns 2.

A return in finally discards the pending return — and pending exceptions. The production variant: mutation in finally affects an already-computed object return, but assignment to the primitive doesn't. If you can explain why both are true simultaneously, you understand the evaluation order.

4. The ternary that boxes one side

Integer val = condition ? 1 : nullObject; — NPE possible.

When one branch is primitive int and the other is boxed, the ternary's type is int — forcing an unboxing of nullObject. The standalone if/else version doesn't have this problem. The spec rule: conditional expressions have a single result type computed at compile time.

5. Arrays.asList is a view, not a list

Arrays.asList(1, 2, 3).add(4) — UnsupportedOperationException. And Arrays.asList(intArray).size() returns 1 — it made a List of int[], not a List of Integer.

The view is fixed-size, backed by the array, writes through. The varargs trap with primitive arrays is the production bug that ships.

The interview meta-skill

Don't recite the trap — derive it live. What is the static type of this expression? Where does boxing happen? Which JLS rule decides? Derivation signals seniority; recitation signals tutorial-following. Every trap above is a two-minute derivation once you ask the right question.

Download this as a free PDF (5 traps + derivation method) — no signup required.


I collected 18 of these — each with the spec-level why and the production-grade fix — in Java Interview Traps. If this post saved you one embarrassed silence, it already paid for itself.

Top comments (0)