Skip to main content
3 of 3
No space before punctation. Correct capitalization. Add tags.
user avatar
user avatar

Stack and Heap memory in Java

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?

Vinoth Kumar C M
  • 15.7k
  • 23
  • 60
  • 86