![]() |
VOOZH | about |
In Java, memory allocation is primarily divided into two categories, i.e., Stack and Heap memory. Both are used for different purposes, and they have different characteristics.
Employee ID: 101 Name: Maddy Salary: 50000.0 Employee ID: 102 Name: Maddy Salary: 60000.0
Memory representation for the above example:
Stack memory is used for method calls, local variables, and references. Memory is automatically allocated when a method starts and cleared when it ends. Data exists only during the method’s execution. If the stack runs out of space, a StackOverflowError occurs.
The sum is: 30
Heap memory is used for objects and instance variables created using the new keyword. The size depends on the class structure. The Garbage Collector manages this area by removing unused objects.
Example: Object in heap
Here, the Scanner object is in the heap, while the reference sc is in the stack.
Note: Garbage collection in the heap ensures automatic memory management.
| Stack | Heap |
|---|---|
| Memory is allocated in a contiguous block. | Memory is allocated in any random order. |
| Allocation and deallocation are automatic (handled by compiler). | Allocation and deallocation are automatic (handled by the Garbage Collector). |
| It is less costly | It is more costly |
| Its implementation is easy | Its implementation is hard |
| Access time is faster | Access time is slower |
Limited memory size may lead to shortage issues. | Can suffer from memory fragmentation due to dynamic allocation. |
| Stack provides excellent memory locality | Heap is adequate but not as efficient |
| Thread safe, data stored can only be accessed by the owner | Not thread safe, data stored is visible to all threads |
| Stack is fixed in size | Heap allows resizing as needed |
| Stack uses a linear data structure | Heap uses a hierarchical data structure |
| Static memory allocation is preferred in an array. | Heap memory allocation is preferred in the linked list. |
| Smaller than heap memory. | Larger than stack memory. |