Chapter 4 · Simulation

Stack and Heap Explorer

← Chapter 4
Correct 0 / 0

Java code

    Memory

    Output (console)

    Stack and Heap Explorer

    Goal: see where variables and objects live in memory in Java. Every method call opens a frame on the stack; local variables and parameters live in that frame. Every object created with new lives on the heap. A variable of a class type does not hold the object itself but the reference (the arrow) to it.

    How to use it

    1. Pick a program from the list at the top.
    2. Step ▶ / ◀ (keyboard → / ←), Play, Reset. The yellow line is the line being executed; the value or arrow that changed last is highlighted in red in memory.
    3. With Test yourself on, you predict the output and which objects can be garbage collected; the number of correct answers is shown at the top.

    The picture

    • The left column is the stack: main at the bottom, the method that is running now on top (red outline). While a constructor runs, its own frame shows the this reference.
    • On the right is the heap: each object is shown with its class name and a number (#1, #2…). The numbers are only for explanation; Java does not show object addresses.
    • A faded object with a dashed outline cannot be reached through any live reference, so it is eligible for garbage collection. It is not known when the collector will remove it, but the program has no way left to reach it.

    Reminders

    • b = a; copies the reference, not the object: both variables point to the same object (aliasing). A change made through one is visible through the other.
    • Java passes everything by value; for a reference type the value passed is the reference. A method can change the fields of an object, but assigning a new object to the parameter does not change the caller's variable.
    • The elements of an object array are references and start out as null; using a field or method through null throws NullPointerException.
    • An object that points to other objects is also eligible for garbage collection once no path leads to it.

    The programs' outputs were checked by compiling with javac --release 8 and running on Java 8.

    Related slides: Chapter 4.1 · Objects and Classes (References, new Car(...): Step by Step, Reference Assignment, null and NullPointerException).