Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests - Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests -

Difference between Stack and Heap Memory in Java

The JVM (Java Virtual Machine) splits the memory into two sections: stack memory and heap memory. Let’s find out some major differences between stack and heap memory in java.

What is Stack Memory in Java?

In java, a stack is a memory that comprises local variables, reference variables and methods. This memory is assembled when a thread is created. Stack memory always prefers the famous LIFO (Last-In-First-Out) order.

What is Heap Memory in Java?

In java, a heap is part of memory that comprises objects and reference variables. Whenever we create objects, it occupies the place in the heap memory; on the other hand, the reference of that object forms in the stack. Like stack, heap does not follow any LIFO order.

Difference between Stack and Heap Memory in Java

S.No. Stack Memory in Java Heap Memory in Java
1. Stack follows the LIFO order. Heap does not follow any order because here, the pattern of memory allocation is not fixed.
2. It stores the entities that have a short life, like variables and methods. Heap stores entities like objects.
3. It is not flexible as we cannot make any changes once the memory allocation is done. It is flexible as we can make changes here even after the allocation of memory.
4. It is faster than heap in terms of allocation and deallocation. It is slower than stack in terms of allocation and deallocation.
5. The size of stack memory is small. The size of heap memory is large.
6. Through the JVM option -Xss, we can improve the size of a stack. Through the JVM options -Xmx and -Xms, we can change the size of a stack.
7. It is affordable. It is affordable as compared to the stack.
8. The implementation part is easy here. The implementation part is tough here.
9. In stack, the memory allotment is continuous. In heap, the memory allotment is random.
10. The allocation and deallocation are automatically performed by the compiler. Here the allocation and deallocation are done manually.

Keep learning and stay tuned to BYJU’S to get the latest updates on GATE Exam along with GATE Eligibility Criteria, GATE 2024, GATE Admit Card, GATE Application Form, GATE Syllabus, GATE Cutoff, GATE Previous Year Question Paper, and more.

Also Explore,

Comments

Leave a Comment

Your Mobile number and Email id will not be published.

*

*