Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and Dynamic memory in Java

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.)?

like image 457
user162114 Avatar asked Feb 23 '26 12:02

user162114


2 Answers

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
  }
}
like image 110
Narendra Pathai Avatar answered Feb 26 '26 02:02

Narendra Pathai


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

like image 45
Tom Avatar answered Feb 26 '26 02:02

Tom