Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Stack vs Heap Memory Allocation
Next article icon

Java Stack vs Heap Memory Allocation

Last Updated : 03 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, memory allocation is primarily divided into two categories, i.e., Stack and Heap memory. Both are used for different purposes, and they have different characteristics.

  • Stack Memory: This memory is used to store local variables, method calls, and reference data during program execution.
  • Heap Memory: This memory is used to store objects and dynamic data allocated at runtime.

Difference Between Stack and Heap Memory in Java

StackHeap
Memory is allocated in a contiguous block.Memory is allocated in any random order.
Allocation and deallocation are automatic (handled by compiler). Allocation and deallocation are manual (handled by programmer).
It is less costlyIt is more costly
Its implementation is easyIts implementation is hard
Access time is fasterAccess time is slower

Limited memory size may lead to shortage issues.

Can suffer from memory fragmentation due to dynamic allocation.

Stack provides excellent memory localityHeap is adequate but not as efficient
Thread safe, data stored can only be accessed by the ownerNot thread safe, data stored is visible to all threads
Stack is fixed in sizeHeap allows resizing as needed
Stack uses a linear data structure Heap uses a hierarchical data structure
Static memory allocation is preferred in an array.Heap memory allocation is preferred in the linked list.
Smaller than heap memory.Larger than stack memory.


Stack and Heap Memory Interaction in Java

The below diagram demonstrates the relationship between stack and the heap memory.

Stack-Vs-Heap-Memory-Allocation


The above diagram illustrates how method calls and local variables are stored in the stack memory, while objects and string literals are stored in the heap memory. The references in the stack point to the respective objects in the heap by showing the relationship between method execution and object storage.

Stack Memory Allocation in Java

Stack memory is temporary memory used for function calls. It automatically allocates memory when a function starts and clears it when the function ends. Programmers do not need to manage it manually. Data in stack memory exists only during the function's execution. If the stack runs out of space, a StackOverflowError occurs.

Example: This example demonstrates the local variable such as method parameters and variables declared inside methods, are stored in the stack memory.

Java
// Java program to demonstrate the  // local variables in the stack memory import java.io.*;  class Geeks  {     public static int add(int a, int b) {        	       	// local variabel are stored in the stack         int res = a + b;         return res;     }      public static void main(String[] args) {                // Local variables are stored in the stack         int a = 10;         int b = 20;         int sum = add(a, b);         System.out.println("The sum is: " + sum);     } } 

Output
The sum is: 30 

Explanation: Here, method parameters and variables a, b, and res are stored in the stack memory. Once the method execution ends, the memory is automatically deallocated.


Heap Memory Allocation in Java

Heap memory play important role in Java. When we create an object using new keyword, memory is allocated for that object in the heap. The size of an object depends on the fields and data types define in its class. The JVM calculates how much space is needed based on the object's structure. Heap Memory is divided into so many regions:

  1. Young Generation: The area within the heap where new objects are generally allocated.
  2. Old Generation: The area within the heap where long lived objects are stored after surviving multiple garbage collection cycle.
  3. Permanent Generation: It stores meta data about classes and methods.
  4. Survivor space: It is a part of heap memory Young Generation where objects that survive garbage collection in the Eden Space are moved.
  5. Code cache: It is the special memory outside the heap where JVM stores optimized code to make programs run faster.

When the "new" is called JVM allocates memory for that object in the heap. The garbage collector automatically deletes objects that are no longer needed.

Scanner sc = new Scanner(System.in)

Here, the Scanner object is stored in the heap and the reference sc is stored in the stack.

Note: Garbage collection in the heap area is mandatory for automatic memory management.


Example: This example demonstrates how objects are stored in the heap while their references are stored in the stack.

Java
// Java program to demonstrate the storage  // of objects in heap memory  import java.io.*;  class Student {     String name;     int age;      Student(String name, int age)     {         this.name = name;         this.age = age;     } }  public class Geeks {     public static void main(String[] args)     {         // Here the student object will be stored in the         // heap memory and the references will be stored in         // the stack memory         Student s = new Student("Ram", 20);     } } 

Explanation: Here, the Student object is allocated in the heap memory. The reference s which points to the object is stored in the stack memory.


Next Article
Java Stack vs Heap Memory Allocation

M

musklf2s
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Heap and Stack Memory Errors in Java
    Memory allocation in java is managed by Java virtual machine in Java. It divides the memory into stack and heap memory which is as shown below in the below media as follows: Stack memory in Java  It is the temporary memory allocation where local variables, reference variables are allocated memory wh
    5 min read
    ShortBuffer allocate() method in Java With Examples
    The allocate() method of java.nio.ShortBuffer Class is used to allocate a new short buffer.The position of the new Buffer will be zero & it's limit is its capacity, though the mark is undefined, and each of its elements is initialized to zero. It will be having a backing array, and the array off
    2 min read
    C++ STL vs Java Collections Framework
    Java and C++ provide their different functionalities and their use cases. When it comes to Data structures and Algorithms Java has a special framework named Java collection framework and C++ provides a library called STL.So let's have a look at what are the different functions, complexities, and wha
    3 min read
    How are Java Objects Stored in Memory?
    In Java, memory management is handled by the Java Virtual Machine (JVM). The breakdown of how objects are stored in memory:All Java objects are dynamically stored in the heap memory.References to these objects are stored in the stack memory.Objects are created using the "new" keyword and are allocat
    5 min read
    How Many Types of Memory Areas are Allocated by JVM?
    JVM (Java Virtual Machine) is an abstract machine. In other words, it is a program/software that takes Java bytecode and converts the bytecode (line by line) into machine-understandable code. JVM acts as a run-time engine to run Java applications. JVM is the one that calls the main method present in
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences