Basic Java – 21 || Stack memory and Heap memory in Java.

Stack memory and Heap memory are the two important components of JVM. Whenever a program execution starts JVM allocates memory to all the class, object, methods, variables.

Stack memory and Heap Memory.

Stack Memory

Basically used for thread execution. It works in LIFO (Last in First Out) manner. As soon as any method encountered JVM allocates memory to the primitive variables in the Stack Memory.

For the non-primitive variables like string or object, JVM allocates memory in Heap but the reference of that remains in the Stack memory for execution.

As soon as the method ends, memory de-allocated and ready for the next method. The size of the Stack is less than the Heap memory.

Heap Memory

Heap memory is bigger than the Stack memory. It loads all the Runtime classes into the heap when we execute the program. All the objects and array would be allocated memory in the heap and available until the program execution completed.

Comparison between Stack and Heap

Stack MemoryHeap Memory
Contains only local primitive variables.Contains objects and non-primitive variables.
Available for current thread.Available for the entire program.
Stack works in LIFO manner.There is no such restriction.
It throws StackOverFlowError when gets full.It throws OutOfMemoryError when gets full.
Size of Stack memory is less and faster than Heap.Size of Heap big than Stack and depends on the OS configuration.

Java Basics:

Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.