By Pankaj Kumar
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 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 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.
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. Let’s go through the steps of the execution of the program.
Based on the above explanations, we can easily conclude the following differences between Heap and Stack memory.
java.lang.StackOverFlowError
whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space
error.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.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
what about static methods and static variables? are they stored in stack or heap memory?
- pk
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
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
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
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
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
Replying to JournalDev
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
Replying to JournalDev
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
Replying to JournalDev
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
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
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
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
Nice Article, I have one question. Do we have separate stack memory for each Thread we create?
- Suraj Shrestha
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
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
Nice Article, I have one question. Do we have separate stack memory for each Thread we create?
- Suraj Shrestha
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
Nice Article my doubt is class Memory{ Memory memory=new Memory(); } where memory is get stored…on heap??
- Amit
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
What is the stack memory allocated to each java program?. What is the size of stack memory?
- Rangrao Patil
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
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
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
How much memory is allocated in heap for String ? for example if i define String name; in class
- Pratap
Loved the way you have written this article. Excellent. Understood the concept. Thanks, Cheers
- Sid
This is good explanation. Can you give explanation on this involving array manipulation?
- Farhan
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
where an object and its reference will create for all type of inner classes ?
- Sumant Dharkar
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
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
Hi , What is about String args[] variable. Will this reference variable will not be listed in stack of main method.
- Dheeraj
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
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
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
String s1=new String(“hello”); As I know two objects will be created…but interviewer asked to prove…Pls help me out @pankaj…
- LittleLion
The way explained is easily grasp difference between Heap Space vs Stack – Memory. thanks for publishing this article.
- Gafoor
Superb Explain Pankaj… After a long time now i got the proper answer HERE… Hats Off to you
- Saurabh
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.