Heap vs Stack
In brief,
Heap
- Any instance/member variables are stored in heap
- created java object is in heap, no matter it is created in a method or not
Stack
- stack stores local primitive variables
- stores the local reference variable which points to object of heap
- last in first out
Example
public void test() {
int i = 1;
Student s = new Student();
}
For above code, int i = 1
is stored in stack,
Student s = new Student()
will create a Student
object in the heap, and there is local reference variable s
in stack.
References
Please refer to following links for more detail:
Written on October 19, 2018