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.