Why do locally declared primitives goes to the stack while locally defined objects goes to the heap?

Viewed 126

In Java, when we locally declare a variable, it goes in the Memory Stack, while locally defined objects goes to the Heap.

public class Clazz {
    private int x;

    // constructors omitted for brevity
}

public void method() {
    Clazz clazz = new Clazz(10); // defining an object - this goes to the heap space
    int y = 10; // declaring a varible - this goes to the memory stack
    clazz.doSomething();
}

Why do objects goes to the heap? Yes, I know that the Memory Stack has the reference to the objects in the heap, but why, unlike the primitives, the object values are stored in the heap?

In other words: why not put them all together, or in the memory stack or in the heap?

Edit:

Ok, got it. It's not a good idea to put the object in the memory stack, but why not put them all together in the heap, then?

This provides a good explanation on what the Heap is and what the Stack is, but unfortunately, doesn't answer my question.

1 Answers

Primitives are a known size, up to 8 bytes. Storing a primitive on the heap would require up to 8 bytes of heap space and 4/8 bytes of stack space to store the reference (which is still required to see if the memory is still referenced - see the comment above by @akuzminykh). So it would potentially double the amount of memory required without giving any benefit. Stack space is also cleared up neatly, without having complex garbage collection, so as well as memory efficiency it also improves processing overhead.

A reference to an object is 4/8 bytes, while the object itself can (in theory) be any size, it would not be good to store this on the stack (as you pointed out).

Related