Reputation: 89
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.)?
Upvotes: 3
Views: 13125
Reputation: 41955
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
}
}
Upvotes: 7
Reputation: 4287
Upvotes: 1
Reputation: 3713
This is the best article I ever read about java memory https://blog.codecentric.de/en/2010/01/the-java-memory-architecture-1-act/ - you should that a look how its managed. Also there is another post regarding to this topic Memory allocation for primitive and reference variables
And, as answer to your question: Local variables are stored on the stack while instance and static variables are stored on the heap.
Upvotes: 0
Reputation: 1846
The stack is where memory is allocated to primitives, and where local variables are stored; also references are passed around on the stack.
The heap is where memory is allocated for objects, which in turn is referred to as heap memory. Static variables are stored on the heap along with instance variables.
Upvotes: 0
Reputation: 3205
Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.
Read more: http://javarevisited.blogspot.com/2013/01/difference-between-stack-and-heap-java.html#ixzz2hhlHV13c
Upvotes: 0
Reputation: 1273
primitive variables and function calls are stored in the stack. objects are stored in the heap.
Upvotes: 3