synopsis · Java for DSA · chapter 1

What Happens in Memory

10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.

  1. what it is

    Each call gets a frame on the stack (parameters + locals). Every new object or array lives on the heap. Variables hold references: arrows to objects.

  2. what it is

    Java is always pass-by-value. For an object, the value copied is the reference: a method can change the object, never the caller's variable.

  3. use it when

    Use long when sums or products can pass ~2.1·10⁹: many big values, a * b above 46,340, prefix sums, mod 10⁹+7 math.

  4. template

    Safe midpoint: int mid = lo + (hi - lo) / 2; or int mid = (lo + hi) >>> 1;

  5. cost

    Passing an array or list to a method is O(1): one reference is copied. Copying it (clone, new ArrayList<>(list)) is O(n).

  6. cost

    Recursion depth d uses O(d) stack. A default 1 MB stack holds roughly 10⁴ simple frames, then StackOverflowError.

  7. trap

    == on objects compares references. Use equals for String/Integer and Arrays.equals for arrays. Literals only look safe because they are pooled.

  8. trap

    result.add(path) stores the same list every time. Snapshot it: result.add(new ArrayList<>(path)).

  9. trap

    (long) (a * b) is too late: the int multiply already wrapped. Write (long) a * b.

  10. pro tip

    Garbage = unreachable. In your own array-backed stack, set items[size] = null after a pop so the GC can free the object.

Shaky on a card? Open the chapter or flip its recall cards.