Memory areas review: trace a whole program
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every idea in this module fits in one picture: frames on each thread's stack, objects on the shared heap, static values with their Class object, class data in Metaspace. Drawing that picture for a whole program, and knowing the two most common wrong ideas about it, covers most JVM memory questions asked in exams and interviews.
Tracing frames, heap objects and static fields for one program
A full trace answers four questions for one marked line: which frames are alive, what each local holds, which objects are on the heap and who refers to them, and what the static fields hold.
Example 1 · A shop order program to trace
import java.util.ArrayList;import java.util.List;
class Order { static int nextToken = 101; // one value for the class final int token; // fields: inside each Order object final String item; final int price;
Order(String item, int price) { this.token = nextToken++; this.item = item; this.price = price; }}
public class ShopTraceDemo { static int bill(List<Order> orders, int discount) { int total = 0; for (Order o : orders) { total += o.price; } return total - discount; // (*) Example 2 draws memory at this line }
public static void main(String[] args) { List<Order> basket = new ArrayList<>(); basket.add(new Order("Notebook", 60)); basket.add(new Order("Pen", 15));
Order last = basket.get(1); int toPay = bill(basket, 5);
System.out.println("Token " + last.token + " is " + last.item); System.out.println("To pay: Rs " + toPay); System.out.println("Next token: " + Order.nextToken); }}Token 102 is Pen To pay: Rs 70 Next token: 103
What this code does
- Two
Orderobjects are created, sonextTokengoes 101, 102 and ends at 103. It is one static value, shared by all orders. lastand the list's second slot point to the sameOrder, solast.tokenis 102.billadds 60 and 15 and takes off 5, giving 70.
Example 2 · The full memory picture at line (*)
Memory at line (*) in bill() (simplified picture, HotSpot)STACK of thread main (top first) HEAP+-----------------------------+| bill() || orders -----------------------> ArrayList#1 [ ref to Order#1, ref to Order#2 ]| discount = 5 || total = 75 |+-----------------------------+| main() || args -----------------------> String[0]| basket -----------------------> ArrayList#1 (the same list)| last -----------------------> Order#2| toPay (not assigned yet)|+-----------------------------+ Order#1 { token=101, item -> "Notebook", price=60 } Order#2 { token=102, item -> "Pen", price=15 }Order's Class object (heap): nextToken = 103Metaspace: class metadata of Order and ShopTraceDemoString pool (heap): "Notebook", "Pen" and the other literalsFrames alive: bill, main. Heap: 1 ArrayList, 2 Order objects, 1 String[] and the strings. Static: nextToken = 103 with Order's Class object.
What this code does
bill'sordersandmain'sbasketare two references to oneArrayList. The loop variableois not drawn because its loop has already finished at line (*).totalanddiscountareintvalues insidebill's frame.toPayhas a slot inmain's frame, but it gets its value only whenbillreturns.
Draw them in that order, as in the Heap versus stack lesson, and add one line each for the static values and Metaspace.
The shop program below is small but has every kind of value: primitives and references in two frames, a list and two objects on the heap, a static counter and string literals. Trace it at line (*) before you look at Example 2.
Mistake: "objects live on the stack"
The wrong idea: an object created inside a method, or an array held by a local variable, lives on that method's stack and dies with it. In Java, new always creates the object on the heap.
Example 3 · Objects outlive the method that created them
import java.util.ArrayList;import java.util.List;
class Seat { final String coach; final int number;
Seat(String coach, int number) { this.coach = coach; this.number = number; }}
public class ObjectsOutliveDemo { static List<Seat> allotSeats(String coach, int count) { List<Seat> seats = new ArrayList<>(); // created inside this method ... for (int i = 1; i <= count; i++) { Seat s = new Seat(coach, i); seats.add(s); } return seats; // frame popped: seats, s and i are gone }
public static void main(String[] args) { List<Seat> booked = allotSeats("S4", 3); for (Seat s : booked) { System.out.println(s.coach + "-" + s.number); }
int[] waitlist = {7, 8}; // an array made in main: also on the heap int[] alias = waitlist; alias[0] = 1; System.out.println("Waitlist starts at " + waitlist[0]); }}S4-1 S4-2 S4-3 Waitlist starts at 1
What this code does
allotSeatscreates a list and threeSeatobjects, then returns. Its frame, withseats,sandi, is gone, but every object is still on the heap and reachable throughbooked.waitlistandaliasare two locals pointing to one array on the heap, so the change throughaliasis seen throughwaitlist.
The frame holds only the reference, and when the frame is popped only that reference disappears.
So a method can build a list of objects and return it, and the objects live on. A local array is not a stack array either: two locals can point to the same array, and a change through one is seen through the other. The only thing that frees heap memory is the garbage collector, once nothing can reach the object.
Mistake: "strings are copied on assignment"
The wrong idea: String b = a; copies the text, so changing b later leaves a alone. The result looks like that, but the reason is different.
Example 4 · String assignment copies the reference
public class StringAssignDemo { public static void main(String[] args) { String a = "Hello"; String b = a; // copies the reference: one String object System.out.println("Same object after b = a? " + (a == b));
b = b + " Pune"; // builds a NEW String; b now points to it System.out.println("a = " + a + ", b = " + b); System.out.println("Same object now? " + (a == b));
StringBuilder x = new StringBuilder("Hello"); StringBuilder y = x; y.append(" Pune"); // but a StringBuilder can change in place System.out.println("x = " + x + ", y = " + y); }}Same object after b = a? true a = Hello, b = Hello Pune Same object now? false x = Hello Pune, y = Hello Pune
What this code does
- After
b = a, there is oneStringobject anda == bistrue.b + " Pune"creates a second object, sobmoves andakeeps the old text. xandyalso share one object, butappendchanges that object in place, so both printHello Pune. Nothing was copied in either case.
b = a copies the reference, so both variables point to one String object, and a == b is true.
Strings cannot be changed. b = b + " Pune" builds a new String and points b at it; a still points to the old one. A StringBuilder can be changed in place, so with two references to one builder, a change through one is seen through the other.
Mixed review and interview drill
Say each answer out loud in one or two sentences, then check it against the module:
- Shared areas: the heap and the method area (Metaspace on HotSpot). Per thread: JVM stack, program counter, native method stack.
- A frame holds parameters, locals and working values for one call; it is popped when the call returns or throws.
- Primitives are stored as values, objects through references, and Java passes both by value.
- Static values sit with the
Classobject on the heap, pooled strings on the heap (since Java 7), class metadata in Metaspace (since Java 8). - Locals are thread-safe; heap objects reachable by several threads are not.
StackOverflowError: a thread's stack.Java heap spaceandGC overhead limit exceeded: the heap.Metaspace: class data.unable to create native thread: too many threads.
Next step
Check your understanding
12 quick questions