How Java Heap and Stack Area Works During Code Execution

How Java Heap and Stack area works during code execution is always been a confusing topic and for most people, understanding about the stack and memory allocation is a bit harder as compared to topics such as polymorphism, threads, exception and etc. In this post, we will see how memory is allocated in stack and heap with examples.

Consider an example -1:

1.class School{}
2.class Student{
3.      School n;                                 //instance variable
4.      String Lname;                            //instance variable
5.      public static void main(String args[]){
6.             Student s;                               //local variable:s
7.             s = new Student();
8.             s.subjects(s);
9.      }
10.     void subjects(Student stud){             //local variable: stud
11.         n = new School();
12.         stud.setName("Alice");
13.   }
14.     void setName(String studLastName){       //local variable: studName 
15.        Lname = studLastName;
16.   }

Stack and Heap

Now let us look at the state of stack and heap:

  • Line 5: main() method is placed on the stack
  • Line 6: Reference variable s is created on the stack, but there is no Student object yet
  • Line 10: The subjects() method is placed on the stack, while the stud parameter as a local variable
  • Line 11: A new School object is created on the heap and assigned to student ‘s instance variable
  • After Line 15 completes, setName() completes and is removed from the stack. At this point, the local variable studLastName disappears too, although the String object it referred to is still on the heap

What is Java Heap space?

  • Heap memory is the runtime data area from which JVM allocates memory for all class instances and arrays
  • Whenever we create an object it is always created in the Heap space and we can also say, the heap is used for dynamic memory allocation
  • Any object created in the heap space has global access and can be referenced from anywhere in the program
  • Heap values, however, exist on the heap at some point and are destructed either by Garbage collector or manually on the other
  • Also, there is no size limit on the heap

What is Java Stack space?

  • This is the temporary memory where variable values are stored when their methods are invoked
  • It is a section of memory which contains methods, local variables, and reference variables
  •  java.lang.StackOverFlowError  occurs when there is no memory left for storing function call or local variable
  • The stack is accessed through LIFO(Last In First Out) memory allocation system
  • Also, the variables stored on the stack are only visible to the owner thread
  • The stack memory grows and shrinks as the push and pop operations are performed by the functions
  • One should also know that stack has size limits, depending upon the type of operating system you use

Octocat - CodedBug github

For some executable examples on this topic refer codedbug Git Repo

Most Frequently asked questions on Memory Allocation in Java?

All instantiation and memory allocation for static variables for all classes in the program is done before running the main method.
The main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java.
If there is no memory left in a stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap memory for creating an object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.
Size of stack memory is very lesser(very less) than the size of heap memory in Java.
The heap is just the area of RAM that is allotted to the JVM by the operating system for runtime activity. As such it is the place that objects get created during a JVM session. While the 'pool' is just a special area of memory that Java sets up to store all String literals.