Static and Dynamic memory in Java

11,530

Solution 1

In one line it depends on where the variable is declared.

Local variables (variables declared in method) are stored on the stack while instance and static variables are stored on the heap.*

NOTE: Type of the variable does not matter.

class A{
  private int a = 10;  ---> Will be allocated in heap

  public void method(){
     int b = 4; ----> Will be allocated in stack
  }
}

Solution 2

primitive variables and function calls are stored in the stack. objects are stored in the heap.

Solution 3

  1. The JVM stack stores local variables.
  2. All class instances and arrays are allocated on the JVM heap.
  3. The Method area stores per class structure
  4. The runtime constants pool stores constants
Share:
11,530
user162114
Author by

user162114

Updated on June 04, 2022

Comments

  • user162114
    user162114 almost 2 years
    int x;
    int y=10;
    

    What type of memory is allocated in Java? I heard that everything in Java is allocated dynamic memory. That is true for objects, but does the same rule follow for primitive data types also (like int, float, etc.)?