Java Heap Space vs Stack - Memory Allocation in Java

Published on August 3, 2022


Java Heap Space vs Stack - Memory Allocation in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometime back I wrote a couple of posts about Java Garbage Collection and Java is Pass by Value. After that I got a lot of emails to explain about Java Heap Space, Java Stack Memory, Memory Allocation in Java and what are the differences between them. You will see a lot of reference to Heap and Stack memory in Java, Java EE books and tutorials but hardly complete explanation of what is heap and stack memory in terms of a program.

Java Heap Space

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create an object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that don’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.

Java Stack Memory

Java Stack memory is used for the execution of a thread. They contain method-specific values that are short-lived and references to other objects in the heap that is getting referred from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as the method ends, the block becomes unused and becomes available for the next method. Stack memory size is very less compared to Heap memory.

Heap and Stack Memory in Java Program

Let’s understand the Heap and Stack memory usage with a simple program.

package com.journaldev.test;

public class Memory {

	public static void main(String[] args) { // Line 1
		int i=1; // Line 2
		Object obj = new Object(); // Line 3
		Memory mem = new Memory(); // Line 4
		mem.foo(obj); // Line 5
	} // Line 9

	private void foo(Object param) { // Line 6
		String str = param.toString(); //// Line 7
	} // Line 8


The below image shows the Stack and Heap memory with reference to the above program and how they are being used to store primitive, Objects and reference variables. java memory management, java heap space, heap vs stack, java heap, stack vs heap Let’s go through the steps of the execution of the program.

  • As soon as we run the program, it loads all the Runtime classes into the Heap space. When the main() method is found at line 1, Java Runtime creates stack memory to be used by main() method thread.
  • We are creating primitive local variable at line 2, so it’s created and stored in the stack memory of main() method.
  • Since we are creating an Object in the 3rd line, it’s created in heap memory and stack memory contains the reference for it. A similar process occurs when we create Memory object in the 4th line.
  • Now when we call the foo() method in the 5th line, a block in the top of the stack is created to be used by the foo() method. Since Java is pass-by-value, a new reference to Object is created in the foo() stack block in the 6th line.
  • A string is created in the 7th line, it goes in the String Pool in the heap space and a reference is created in the foo() stack space for it.
  • foo() method is terminated in the 8th line, at this time memory block allocated for foo() in stack becomes free.
  • In line 9, main() method terminates and the stack memory created for main() method is destroyed. Also, the program ends at this line, hence Java Runtime frees all the memory and ends the execution of the program.

Difference between Java Heap Space and Stack Memory

Based on the above explanations, we can easily conclude the following differences between Heap and Stack memory.

  1. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
  2. Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
  3. Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
  4. Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
  5. Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
  6. We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
  7. When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
  8. Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.

That’s all for Java Heap Space vs Stack Memory in terms of java application, I hope it will clear your doubts regarding memory allocation when any java program is executed.

Reference: https://en.wikipedia.org/wiki/Java_memory_model.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
DigitalOcean Employee
DigitalOcean Employee badge
May 17, 2021

Hello Sir, Is there any way I can download these interview question and answer in pdf format? All Questions from core java to Heap and stack memory!.. Let me know if there is a way!

- Pallavi

    DigitalOcean Employee
    DigitalOcean Employee badge
    July 14, 2020

    Thank you for your article I have a question. I wonder if xxxx.toString() automatically registers value itself to String Pool. I remember another column in some where, it explained that if we want to use xxxx.toString() often, we need to add itern() method to that value like this : xxxx.toString()

    - Paik

      DigitalOcean Employee
      DigitalOcean Employee badge
      July 1, 2020

      very nicely explained thanks!

      - unnamed

        DigitalOcean Employee
        DigitalOcean Employee badge
        January 7, 2020

        Thanks a lot, sir. can you please explain, when a static variable comes in it loads at the class area. Where is the class area?

        - sinthujan

          DigitalOcean Employee
          DigitalOcean Employee badge
          December 17, 2019

          How does heap space look like during polymorpohism in java specially in case of upacasting?

          - VISHAL PUNIR

            DigitalOcean Employee
            DigitalOcean Employee badge
            December 2, 2019

            what is java.lang.object@57? why is it in String pool .

            - JIT

              DigitalOcean Employee
              DigitalOcean Employee badge
              August 7, 2019

              Hi Pankaj, Very nice explanation and logical. Makes sense. https://stackoverflow.com/questions/57380797/cannot-reach-a-temp-table-using-java-sql-statement-object-passed-as-a-map-value In this problem, what would you say has happened for memory allocation? a) new HashMap() means a new object in the heap. and stack has reference to it. b) put(key,value) means the value of the reference to the object. However, it seems the object cannot reach certain memory references if retrieved from within the HashMap. Would you be able to shed some light on that?

              - M. Manna

                DigitalOcean Employee
                DigitalOcean Employee badge
                July 12, 2019

                Hi pankaj, As per above explanation ,you said that inside method local variables and data will be stored in stack but if created an object inside a method where will it store. is it store in stack or heap because its a local object? Regards, Gopi Reddy

                - Gopi Reddy

                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 13, 2019

                  What would be more efficent, declaring variable inside loop or outside? How Java handles this? Outside but once seems to be better, right? But is it really? Example1: for(int i=0; i< 1000000; i++) { int x = 0; //rest of code using ‘x’ variable } Example2: int x = 0; for(int i=0; i< 1000000; i++) { //rest of code using ‘x’ variable }

                  - DamianPL

                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 1, 2019

                    As far as I understand both stack and heap memory stored in the RAM and difference is only in kind of interaction with that memory: random access with heap and LIFO with stack. Is it true?

                    - Dmitrii

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel