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:

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

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?