Stack and Heap Memory Management in Java

garbage-collectionheapjavamemorystack

As I understand, in Java, stack memory holds primitives and method invocations and heap memory is used to store objects.

Suppose I have a class

class A {
       int a ;
       String b;
       //getters and setters
}
  1. Where will the primitive a in class A be stored?

  2. Why does heap memory exist at all? Why can't we store everything on the stack?

  3. When the object gets garbage collected, is the stack associated with the objected destroyed?

Best Answer

The basic difference between stack and heap is the life cycle of the values.

Stack values only exist within the scope of the function they are created in. Once it returns, they are discarded.
Heap values however exist on the heap. They are created at some point in time, and destructed at another (either by GC or manually, depending on the language/runtime).

Now Java only stores primitives on the stack. This keeps the stack small and helps keeping individual stack frames small, thus allowing more nested calls.
Objects are created on the heap, and only references (which in turn are primitives) are passed around on the stack.

So if you create an object, it is put on the heap, with all the variables that belong to it, so that it can persist after the function call returns.