← Java Memory · guided lesson
What Happens in Memory
the story
Call stack & heap
Every tool here exists because something was too slow or broke without it. Here is what.
Early programs gave each subroutine one fixed block of working memory. A subroutine could not be called again before it finished, because the new call would overwrite the old one's data. In "Recursive Programming" (1960), written for ALGOL 60 compilers, Dijkstra kept each call's data on a stack instead: push a fresh area on every call, drop it on return. The JVM works the same way today: every thread has a stack of frames, and objects live on a shared heap.
the problem it solved
Let methods call each other, and themselves, without overwriting each other's local variables, and free that memory the instant a call returns.
why it matters: without it
Without a frame per call, no method could call itself, so no tree DFS and no backtracking. Without a heap, nothing could outlive the method that made it: no linked lists, no HashMaps.
sources: E. W. Dijkstra, "Recursive Programming", Numerische Mathematik 2 (1960) ↗ · JVM Specification (Java SE 17), §2.5 Run-Time Data Areas and §2.6 Frames ↗ · The java command (JDK 17): -Xss default thread stack size ↗
also in this chapter: References & pass-by-value · Fixed-width integers & overflow · Garbage collection
the idea
The idea in 30 seconds
Every method call gets a frame on the call stack for its parameters and local variables. The frame disappears when the method returns.
Every object you create with new, every array included, lives on the heap. A variable of object type holds only a reference: an arrow to it.
Java always copies the value into a parameter. For an object, that value is the arrow, so a method can change the object but never the caller's variable.
picture this
Desktop shortcuts in Windows: the shortcut (a reference in your frame) is tiny and points at a real folder (the object on the heap). Copy the shortcut and both copies open the same folder, so a file added through one shows up in the other. Deleting a shortcut never deletes the folder.
watch it
Call stack and heap, frame by frame
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
Call stack and heap, frame by frame
Boxes on the left are frames and their variables, spheres on the right are heap objects, arrows are references. Watch the array outlive the method that made it.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
watch it
Pass-by-value: swap fails, arr[i] = … works
Predict mode is on. Before each step, guess what happens, then watch. Wrong guesses are fine; that is how it sinks in.
Pass-by-value: swap fails, arr[i] = … works
swap gets copies of two numbers. swapInArray gets a copy of an arrow to the caller's array. reassign repoints only its own arrow.
On this screen ← / → step the simulation. Use the buttons below to move through the lesson.
key idea 1 of 8
Read it once. Say it out loud once. Bas.
Stack: one frame per running call, holding parameters, locals and partial results. Push on call, pop on return. Small: 1 MB per thread by default on 64-bit Linux and macOS.
key idea 2 of 8
Read it once. Say it out loud once. Bas.
Heap: every object and array (new). Shared, much bigger, and cleaned by the garbage collector once nothing can reach an object.
key idea 3 of 8
Read it once. Say it out loud once. Bas.
Primitive vs reference: an int variable holds the number itself. An int[], String or ListNode variable holds a reference (or null).
key idea 4 of 8
Read it once. Say it out loud once. Bas.
Always pass-by-value. swap(int a, int b) swaps copies. arr[0] = 99 inside a method changes the caller's array, because both arrows point at one array. arr = new int[5] inside the method changes nothing outside.
key idea 5 of 8
Read it once. Say it out loud once. Bas.
`==` compares what the variables hold: values for primitives, references for objects. Compare contents with equals (Arrays.equals for arrays).
key idea 6 of 8
Read it once. Say it out loud once. Bas.
`int` is 32 bits: about ±2.1·10⁹, and it wraps around silently. Widen to long before the operation, and write midpoints as lo + (hi - lo) / 2.
key idea 7 of 8
Read it once. Say it out loud once. Bas.
Arrays are objects: b = a copies the reference; a.clone() copies the contents; an int[][] is an array of references to separate rows.
key idea 8 of 8
Read it once. Say it out loud once. Bas.
Recursion depth = stack frames. Roughly 10⁴ simple frames fit in the default stack; deeper inputs need a loop or an explicit ArrayDeque.
spot the pattern
When you see this, think this
Constraints like
nums[i] ≤ 10⁹and you add or multiply valueslongsums and(long) a * bBinary search on indices or on an answer range near 2³¹
lo + (hi - lo) / 2, never(lo + hi) / 2"Modify in place" and the method returns
voidChange the array's contents through the reference you were given
A helper needs to give back two numbers
Return an
int[]or a record; int parameters are copies
+3 more signals on the chapter page
watch out
A trap or two
Many wrong answers in interviews come from small slips like these, not from the hard part.
- Expecting
swap(int a, int b)orcount++inside a method to change the caller's variables. - Reassigning a parameter (
arr = new int[n],head = head.next) and expecting the caller to see the new object.
quick check
One question. No pressure.
int x = 1, y = 2; swap(x, y); where swap exchanges its two int parameters. What are x and y afterwards?
now try
Your first real problem
You know enough to try this one. Stuck? Use the hints; that is what they are for.
Binary Search
Write the midpoint as lo + (hi - lo) / 2 and say why out loud: lo + hi can overflow.
recall
Flip a few cards
Answer in your head first, then flip. Grade yourself honestly; the schedule brings back what you forget.
Where do a method's local int and its int[] arr = new int[n] live?
Question 1: Where do a method's local int and its int[] arr = new int[n] live?
done
Lesson complete
Chalo, that is the core. The full chapter has the rest: cost tables, Java details and more problems.