Many frames, one heap
Each recursive frame keeps its own local; all of them write into the same heap array.
A running Java program keeps method calls and their local variables on a per-thread stack, and all objects and arrays on a shared heap. Locals hold primitive values or references; the objects those references point to live on the heap until the garbage collector reclaims them.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a program where a method makeGreeting(String name) builds and returns a String, and main prints it. In comments, mark which variables are in which frame and which objects are on the heap.
Predict the output, then run: int[] a = {1, 2}; int[] b = a; a = new int[] {9, 9}; System.out.println(b[0] + " " + a[0]);
Write a method static int[] counter() that keeps a running count across calls by storing it in an array held in a static field, and call it three times, printing the count each time.
Explain it without notes
What is stored on the stack and what on the heap in a running Java program?
When makeScores returns an array it created, why is the array still usable by the caller?
When does an object become eligible for garbage collection?
What's the difference between StackOverflowError and OutOfMemoryError: Java heap space, and how do you fix each?
Why are local variables thread-safe while objects may not be?
Expected output
frame for index 3 still has local = 9
frame for index 2 still has local = 4
frame for index 1 still has local = 1
frame for index 0 still has local = 0
heap array: [0, 1, 4, 9]