Heap and Stack Memory in Java


Heap and stack memory are both used during program execution, each serving a distinct purpose.
Stack
- Stack memory is used for method execution. Every time a method is called stack memory is used
- It stores local variable, method call and reference variable. - Every time a method start executing, it gets pushed into stack memory, and after execution, it is popped out. This follow the LIFO (Last In, First Out) approach. - Each thread has its own stack memory, which provide thread safety. - Memory is automatically cleared once the method execution is complete. - Stack memory is fast due to its simplicity and automatic cleanup.
Heap - Heap memory is used storing objects and their instance variables. - Whenever a object is created using new keyword it get stored in the heap memory.
- Heap memory is shared among all threads, so it is not thread-safe by default. - Memory in heap is managed and cleared by garbage collector. - Heap is slower than stack because of random access and garbage collection overhead.
Subscribe to my newsletter
Read articles from Harshit Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
