Skip to main content

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 cant we store everything in 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