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.
- what it is
Each call gets a frame on the stack (parameters + locals). Every
newobject or array lives on the heap. Variables hold references: arrows to objects. - 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.
- use it when
Use
longwhen sums or products can pass ~2.1·10⁹: many big values,a * babove 46,340, prefix sums, mod 10⁹+7 math. - template
Safe midpoint:
int mid = lo + (hi - lo) / 2;orint mid = (lo + hi) >>> 1; - 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). - cost
Recursion depth d uses O(d) stack. A default 1 MB stack holds roughly 10⁴ simple frames, then
StackOverflowError. - trap
==on objects compares references. UseequalsforString/IntegerandArrays.equalsfor arrays. Literals only look safe because they are pooled. - trap
result.add(path)stores the same list every time. Snapshot it:result.add(new ArrayList<>(path)). - trap
(long) (a * b)is too late: the int multiply already wrapped. Write(long) a * b. - pro tip
Garbage = unreachable. In your own array-backed stack, set
items[size] = nullafter a pop so the GC can free the object.
Shaky on a card? Open the chapter or flip its recall cards.