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.
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.
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
Awesome ! best place to brush up concepts !
- Sorrowfull Blinger
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 for your articles. They are very usefull!
- Dmitry
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
Nice artical , greate and simple explanation .
- Vishnu
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
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