Tutorial

Java Heap Space vs Stack - Memory Allocation in Java

Published on August 3, 2022
author

Pankaj

Java Heap Space vs Stack - Memory Allocation in Java

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
		System.out.println(str);
	} // 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 author(s)

Category:
Tutorial

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 19, 2014

what about static methods and static variables? are they stored in stack or heap memory?

- pk

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 31, 2016

class structure and static variables are stored in a separate memory pool area known as Method Area.

- Sankar

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 31, 2017

    Static Variables are stored in HEAP. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap. https://net-informations.com/java/cjava/memory.htm John

    - johnsonjeven

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 20, 2014

      This is very useful. Thanks for your great work. public static void main(String[] args) - what about args? It is stored in stack right?

      - kanaga

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 28, 2014

        Awesome ! best place to brush up concepts !

        - Sorrowfull Blinger

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 1, 2014

          On the public static void main(String[] args) - Does the memory for args[] allocated in heap space but the reference is allocated in Stack - Is my understanding correct?

          - Shaik

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 1, 2014

          Yes, it’s String array… hence Object, so stored in Heap memory. However main method contains the references in stack memory.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 4, 2014

            Thanks for your articles. They are very usefull!

            - Dmitry

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 28, 2014

              Thanks a lot Pankaj. This article is very great! Can You write a article about Thread-Safe? Because I don’t know Why a global variable is not-thread-safe. I reseach very much about it. I use “new” operation but a global variable in that class, it’s not Thread-Safe. Thanks in advance!

              - i_know_nothing

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 20, 2014

                This is a very nice explanation of Stack and Heap Memory and their differences. I wish you could write a bit about instance variables and static variables. Well Done !

                - Abhishek Thakur

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 27, 2014

                  Nice artical , greate and simple explanation .

                  - Vishnu

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 2, 2014

                    Thank you for sharing this article. One point i have to raise here. regarding “int i = 1”. Not sure if this is because of “escape analysis” or something else like “interning”. But what i tested it goes to “Heap”. Following is my test: package immutable; public class Immutable_One { private int i = 2; public int get() { return i; } } package immutable; public class Immutable_Two { private int j = 2; public int get() { return j; } } package immutable; public class ImmutableTest { public static void main(String[] args) { Immutable_One immutable_One = new Immutable_One(); int i = immutable_One.get(); Immutable_Two immutable_Two = new Immutable_Two(); int j = immutable_Two.get(); if (i == j) { System.out.println("Equal"); } else { System.out.println("NOT Equal"); } } } The result comes “Equal”.

                    - Arfeen

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 4, 2014

                    Its basically because of the caching. If we open the Integer class, you can see that value between -128 to 127 are cached. In the above program if you put any value outside of the range, you will the desired behavior. So as per my thought- What Pankaj mentioned in picture “int i = 1” as part of stack, that must be re-corrected and move it to heap area which can be shared among all thread.

                    - Tanzy

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 23, 2015

                      I don’t see how this is a valid test. You’re comparing the value of two primitives, which is a straight up comparison of their values. No references involved at that point. For a better test, make i and j Integer objects, and return Integer objects. Than you’ll see the caching behavior that Tanzy mentions.

                      - cc10123

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      March 27, 2016

                      Agree. He is just comparing primitive values, 2 == 2 returns true. He should try something like this: Integer a = Integer.valueOf(2); Integer b = Integer.valueOf(2); System.out.println(a.equals(b)); // comparing values System.out.println(a==b); // comparing references Integer c = new Integer(2); Integer d = new Integer(2); System.out.println(c.equals(d)); // comparing values System.out.println(c==d); // comparing references

                      - Michael

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        December 6, 2014

                        If it were truly “pass by value” as in the case with c++ then it would be a copy/clone of the object. Calling the foo() method would not affect the blue balloon color value in the main method. But in the example it does because it is “referencing” the memory space in the heap and changing the value. Much like you would when “passing by reference”. However, I also see the point of how the value is used (as if a copy/clone were passed in) in the swap method. The manipulation of the balloon colors in the swap method does not affect the balloons variables in the main method. Its almost like its “pass by reference or value”. In either case the presentation was awesome as well as the write up. Thanks for your efforts.

                        - Alalonks

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          December 14, 2014

                          Crisp, Clear and to the point…great article. keep rocking!!!

                          - Sudhakar

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            December 16, 2014

                            I have a doubt in static reference and static primitive. public static A a = new A(); public static int b = 5; where ‘a’ reference and ‘b’ primitive live (stack or heap). When it will eligible for garbage collection.

                            - Vel

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              January 4, 2015

                              Nice Article.

                              - Prabhath

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                January 13, 2015

                                Very well explained, thanks!

                                - Pieter

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  February 17, 2015

                                  Nice video, thanks !

                                  - Upir

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    February 27, 2015

                                    Java is not only “Pass by Value”, it’s also “Pass by Reference” which depends if primitives are passed or reference objects (the name implies it). If Java would be purely “Pass by Value“, the following program public class Test { public static void main(String[] args) { Integer i = 2; System.out.println("i initialized = " + i); List u = new ArrayList(Arrays.asList(“1”, “2”, “3”)); System.out.println("u before method = " + u); test(i); test1(u); System.out.println("i outside method = " + i); System.out.println("u AFTER method call = " + u); } private static void test1(List u) { u.add(“blah”); System.out.println("u inside method = " + u); } private static void test(int i) { i = i + 1; System.out.println("i inside method = " + i); } } …would not print u inside method = [1, 2, 3, blah] […] u AFTER method call = [1, 2, 3, blah]

                                    - Alexander Orlov

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    August 23, 2015

                                    In the test(int i) method, when i is being printed its the local variable value which is a copy of i in main(), coming back in main() when i is printed the value still remains same hence its PassByValue.

                                    - Purnendu Dutta

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 7, 2017

                                      In both cases it’s pass by value. In case of ‘i’, value of ‘i’ is copied in the method ‘test()’. In case of ‘u’, value of ‘u’ which is a reference, is copied in method ‘test1()’. Check this code: public static void main(String[] args) { List list = Arrays.asList(“One”, “Three”, “Five”); passByReferenceTest(list); System.out.println(list); // n1: What is printed here? } private static void passByReferenceTest(List list) { list = Arrays.asList(“Two”, “Four”, “Six”); // n2 } If pass by reference was possible then the assignment at line n2 would have changed the list reference in main() and therefore “Two”, “Four”, “Six” would have been printed at line n1. Pointers in C behave like that.

                                      - Miroslav Manchev

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        May 16, 2015

                                        Nice Article, I have one question. Do we have separate stack memory for each Thread we create?

                                        - Suraj Shrestha

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          May 22, 2015

                                          Thanks man, you made my day :D

                                          - Huy

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            May 26, 2015

                                            Thanks dude. Thanks for explaining it neat and clear… (y) cheers!

                                            - Arjun

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              June 13, 2015

                                              Very well! I learn o lot form this passage!

                                              - YangFang

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                June 29, 2015

                                                Very nice and useful Information… Thanks a lot :)

                                                - Subrahmanyam

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  July 24, 2015

                                                  easily i got understand by reading this… thanks to clear my doubt

                                                  - shneha

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    August 4, 2015

                                                    not all objects allocated in Heap ! but static ones , you created Memory and Object instances in a static context so the variables in that context created in heap ! if you create them in foo method stack memory will be used , please correct this big wrong article!!!

                                                    - z6qc@yahoo.com

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    August 5, 2015

                                                    i have no idea what you are talking here.

                                                    - Pankaj

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    December 4, 2015

                                                    We mean that in foo(Object param) here param is a local variable of type Object in foo() so it won’t get space in heap but according to ESCAPE ANALYSIS(by java 6e14) that param will be treated similar to those local variables of primitive types in foo() and gets space in stack and not in heap.!! Will you please clear this out Sir. Thank You.

                                                    - PriyaYT

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    November 10, 2016

                                                    You are right…but escape analysis is not always possible, In this trivial case it was easy for the compiler to find out.

                                                    - Anirban Pal

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      September 1, 2015

                                                      Nice Article my doubt is class Memory{ Memory memory=new Memory(); } where memory is get stored…on heap??

                                                      - Amit

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      September 20, 2015

                                                      stack

                                                      - satyam

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      November 23, 2015

                                                      Heap. The Memory object would always be created on the heap, regardless of where its reference lives. In your example, the memory (small ‘m’) reference is also on the heap, because it exists as part of the Memory class which is on the heap.

                                                      - cc10123

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        September 14, 2015

                                                        You mentioned stand alone program. So My question is once application finish executing, what will happen to String pool, it will be memory or it will remove from heap?

                                                        - Shambhu

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        September 14, 2015

                                                        Once application is finished executing, JVM terminates and all the memory is released to OS.

                                                        - Pankaj

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          September 20, 2015

                                                          simplicity makes this article awesome

                                                          - satyam

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            October 7, 2015

                                                            thnks a lot

                                                            - selvi

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              October 9, 2015

                                                              Awesome explanation, thank you so much.

                                                              - Krishna

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                October 23, 2015

                                                                Very well explained

                                                                - Akanksha

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  December 3, 2015

                                                                  What is the stack memory allocated to each java program?. What is the size of stack memory?

                                                                  - Rangrao Patil

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    December 9, 2015

                                                                    very good explanation. keep it up!

                                                                    - varun

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      December 13, 2015

                                                                      Hi, I have one question. i faced this question in one of the interview, String s1=new String(“abc”); String s2=new String(“abc”); int a=10; int b=10; if a==b is true then why s1==s2 is false

                                                                      - arun

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      December 13, 2015

                                                                      1. int is not an object, java handles primitive data types differently, reducing memory footprint by caching the variables, something like String Pool. 2. String is an object, when new operator is used then a new variable is created rather than checking in String Pool to find some already existing one. Based on above points, I think you can clearly see the reason behind the program output.

                                                                      - Pankaj

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      January 8, 2016

                                                                      StringBuilder sb1 = new StringBuilder(“Niraj”); StringBuilder sb2 = new StringBuilder(“Niraj”); System.out.println("sb1.equals(sb2) "+(sb1.equals(sb2))); Then why this is give “false”

                                                                      - Niraj

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      January 15, 2016

                                                                      That gives ‘false’ because you are comparing two unique StringBuilder objects, not the actual String values. If you changed your code to this: sb1.toString().equals(sb2.toString()) That should give you ‘true’. Remember, when you have an object (like String) it has an object reference (or ID) as well as an actual “value”. If you compare the object references, you will find they are different, even if the object values are the same.

                                                                      - Alex

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        January 8, 2016

                                                                        Great work…written in simple way to understand it :) You can add some advanced level theory also later to make this article perfect like…static/non static context etc

                                                                        - Swapnil Suhane

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          January 9, 2016

                                                                          Thanks a lot, very well framed. Easy & Simple to understand

                                                                          - Jinesh

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            January 16, 2016

                                                                            Very good explanation . Keep doing a great job !

                                                                            - Lucian

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              January 28, 2016

                                                                              Hello Pankaj, Above explanation of memory allocation is very nice and useful. But I am still confused for following scenario : Class A { public A(){…} public void test(){…} public void test1(){…} } class B extends A { public B(){…} public void test(){…} public void test2(){…} } now in main method I am creating object in this way : A a = new B(); a.test(); a.test1(); a.test2(); so how memory allocation will work ? Thanks in Advance.

                                                                              - Sushant

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              February 5, 2016

                                                                              that is not going to compile cause class A doesn’t have test2() method.

                                                                              - mista

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                March 3, 2016

                                                                                How much memory is allocated in heap for String ? for example if i define String name; in class

                                                                                - Pratap

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  April 1, 2016

                                                                                  Well done! This really helped me.

                                                                                  - CS Student

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    April 11, 2016

                                                                                    Excellent Boss !!! clear explanation

                                                                                    - Ram

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      April 12, 2016

                                                                                      Loved the way you have written this article. Excellent. Understood the concept. Thanks, Cheers

                                                                                      - Sid

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        April 13, 2016

                                                                                        This is good explanation. Can you give explanation on this involving array manipulation?

                                                                                        - Farhan

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          April 25, 2016

                                                                                          Good work!? Thank you…☺

                                                                                          - Sarvesh Singh

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            May 15, 2016

                                                                                            Java is both *Pass by value* and *Pass by reference* why baloon.setColor(“Red”); changed the value of color to “Red” when printed in main() method?

                                                                                            - Selvakumar Esra

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              June 3, 2016

                                                                                              where an object and its reference will create for all type of inner classes ?

                                                                                              - Sumant Dharkar

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                June 20, 2016

                                                                                                Where would the references to an Object which is an instance variable be stored. For eg. Class Memory{ Memory mem = new Memory(); public Memory(){ } } So, where would be the “mem” reference be stored as it is not tied to any code/method.

                                                                                                - Melwin

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                August 5, 2016

                                                                                                It would be stored in the heap along with all the other contents (instance primitive variables) in the heap.

                                                                                                - Satishchandra Singh

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  July 5, 2016

                                                                                                  I want to ask how we can elaborate using stack memory and heap memory that two methods are accessing to the same object means (This Reference and Other References to the same object at method level). The purpose is that we want to see the dependencies between two methods using same data.

                                                                                                  - Mrs Afzal

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    August 5, 2016

                                                                                                    Hi , What is about String args[] variable. Will this reference variable will not be listed in stack of main method.

                                                                                                    - Dheeraj

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      August 8, 2016

                                                                                                      I watched the video. It’s excellent. But I have a question about who collects Stack Memory? Refrences will always be in the Stack and as soon as the refrence goes out of scope object is available for the Garbage collection but what happens to the refrence memory in the stack?

                                                                                                      - Jim Mehta

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      August 28, 2016

                                                                                                      Stack frame memory gets deallocated automatically when method exists, because it’s get popped from the stack.

                                                                                                      - andrey

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        August 9, 2016

                                                                                                        Thank for your great work! This is interesting!

                                                                                                        - rungrengreng

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          September 22, 2016

                                                                                                          Nice article. a small suggestion in diagram… can you write steps 1,2,3… so that when step 7 occurs where is the flow can be easily referred for beginners

                                                                                                          - Reddeppa Kande

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            September 25, 2016

                                                                                                            Good work boss…

                                                                                                            - Nagaraju

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              September 29, 2016

                                                                                                              Hi Thanks for this awesome brief about heap and stack memory. [Based on the above explanations, we can easily conclude following differences between Heap and Stack memory. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.] Question: Block for main thread always exists. So as per me stack memory is used only by one thread of execution is not totally correct. Please explain me if I am wrong.

                                                                                                              - Prabhat Kumar

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                October 12, 2016

                                                                                                                String s1=new String(“hello”); As I know two objects will be created…but interviewer asked to prove…Pls help me out @pankaj

                                                                                                                - LittleLion

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                October 18, 2016

                                                                                                                java creates an object xyz in memory and then a x object which has the ingredients of object xyz. Then xyz is destryed (lost). So at the end we created 2 object but now we have one !

                                                                                                                - Rakesh

                                                                                                                  JournalDev
                                                                                                                  DigitalOcean Employee
                                                                                                                  DigitalOcean Employee badge
                                                                                                                  November 2, 2016

                                                                                                                  The way explained is easily grasp difference between Heap Space vs Stack – Memory. thanks for publishing this article.

                                                                                                                  - Gafoor

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    November 3, 2016

                                                                                                                    Great explanation!

                                                                                                                    - Jun Hua

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      November 3, 2016

                                                                                                                      Superb Explain Pankaj… After a long time now i got the proper answer HERE… Hats Off to you

                                                                                                                      - Saurabh

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        November 22, 2016

                                                                                                                        Wonderful explanation

                                                                                                                        - Sailaja Gudala

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          December 3, 2016

                                                                                                                          Thanks Pankaj. You explained a lot in less time and easy manner.

                                                                                                                          - Ajay

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            January 11, 2017

                                                                                                                            Very good!

                                                                                                                            - fred

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            January 19, 2017

                                                                                                                            Stack memory is static, and heap memory is dynamic.(then read properly what is written) Second -_ why a method always contain 2 stack, if that method has no body. Third-- difference between iload and aload. How it is used in stack. If any one plz explain.

                                                                                                                            - Sanjeev

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              January 17, 2017

                                                                                                                              Hi Pankaj, Its very nice explanation you have given. But I have small query about below code, public class MemoryMgmt { static Integer a = new Integer(12); public static void main(String[] args) { Integer b = new Integer(12); int c = 12; System.out.println("a==b "+(a==b)); System.out.println("b==c "+(b==c)); System.out.println("a==c "+(a==c)); } } Can you please explain the memory allocation, where those variables are stored in memory.

                                                                                                                              - Santhosh

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              April 21, 2017

                                                                                                                              It’s very easy to understand. can you please notify which one is best? Stack or Heap

                                                                                                                              - Tamil

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                January 20, 2017

                                                                                                                                Thank you !

                                                                                                                                - Eric Wang

                                                                                                                                  JournalDev
                                                                                                                                  DigitalOcean Employee
                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                  January 31, 2017

                                                                                                                                  Its very nice explanation.

                                                                                                                                  - Narendar

                                                                                                                                    JournalDev
                                                                                                                                    DigitalOcean Employee
                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                    February 1, 2017

                                                                                                                                    if we declare a variables in static method then wether it stores on heap or stack. Please explain me.

                                                                                                                                    - Murugesh

                                                                                                                                      JournalDev
                                                                                                                                      DigitalOcean Employee
                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                      February 2, 2017

                                                                                                                                      Thanks pankaj that was very useful. I have related question if you could help. I have a PatriciaTrie list that holds item but there is not limit to the no of item . so when the item size is huge it throws Java heap error . there no way to increase it any more using -Xms am-Xmx . the only thing is that should be cached and proper message to be shown to the user (now it gives me a internal error which is not useful to the user). But the problem is i am not able to catch this exception. Any suggestions.

                                                                                                                                      - sanjay

                                                                                                                                        JournalDev
                                                                                                                                        DigitalOcean Employee
                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                        February 6, 2017

                                                                                                                                        nice!

                                                                                                                                        - Rajat

                                                                                                                                          JournalDev
                                                                                                                                          DigitalOcean Employee
                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                          February 25, 2017

                                                                                                                                          wow, I’m impressed, looks like one of the best examples I’ve seen so far (and I’ve seen quite a few).

                                                                                                                                          - Lukasz

                                                                                                                                            JournalDev
                                                                                                                                            DigitalOcean Employee
                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                            March 2, 2017

                                                                                                                                            Great explanation . I feel the following link would complete this topic. https://www.mkyong.com/java/find-out-your-java-heap-memory-size/

                                                                                                                                            - Parjanya Roy

                                                                                                                                              JournalDev
                                                                                                                                              DigitalOcean Employee
                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                              March 15, 2017

                                                                                                                                              nice tutorial thanks

                                                                                                                                              - chandan

                                                                                                                                                JournalDev
                                                                                                                                                DigitalOcean Employee
                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                April 6, 2017

                                                                                                                                                Very nice Example…good

                                                                                                                                                - Jitendra Nandiya

                                                                                                                                                  JournalDev
                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                  April 21, 2017

                                                                                                                                                  Very Nice Explanation … Thank you

                                                                                                                                                  - lova

                                                                                                                                                    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!

                                                                                                                                                    Become a contributor for community

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

                                                                                                                                                    DigitalOcean Documentation

                                                                                                                                                    Full documentation for every DigitalOcean product.

                                                                                                                                                    Resources for startups and SMBs

                                                                                                                                                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                                                                    Get our newsletter

                                                                                                                                                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                                                                    New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                                                                    The developer cloud

                                                                                                                                                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                                                                    Get started for free

                                                                                                                                                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                                                                    *This promotional offer applies to new accounts only.