Video in progress

In the following method, which values are stored on the stack and which on the heap?

void checkout() {
    int qty = 3;
    double price = 12.5;
    String name = "Kitob";
    Order order = new Order(name, qty, price);
}

price and qty are on the stack as primitive local variables. The name and order references are also on the stack, but the String and Order objects they point to are on the heap; the fields inside Order are on the heap with the object.

📖 Answer

The rule is simple: a local variable lives in the stack frame, and an object is always on the heap.

  • qty, price: primitives, the value itself is in the frame;
  • name: only a reference in the frame. The "Kitob" literal is an object in the string pool, which is on the heap;
  • order: a reference in the frame, and new Order(...) is on the heap;
  • the int qty and double price fields inside Order: even though they are primitives, they are on the heap, because they are part of the object.

People often slip here in interviews: the statement "primitives are always on the stack" is wrong. A primitive field sits on the heap with its object, and a static primitive field is on the heap too (next to the class's Class object).

When the method ends, the frame disappears. If nobody else references the Order object, it gets collected in the next GC.

One note: through escape analysis, the JIT may not create an object that never leaves the method on the heap at all. But that is an optimization, not a language rule.