When a Java program starts Java Virtual Machine gets some memory from the Operating System. Java Virtual Machine or JVM uses this memory for all its needs. This memory is basically divided into two-part
- Java Heap Space
- Java Stack Memory
Java Heap Space
- Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
- Whenever we create an object using the new keyword, it’s always created in the Heap space.
- Any object created in the heap space has global access and can be referenced from anywhere of the application.
Java Stack Memory
- 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.
- A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one end.
- In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap.
- An object can be stored on the stack. If you create an object inside a function without using the “new” operator then this will create and store the object on the stack, and not on the heap.
- So, the object “m” is destroyed once the function has run to completion – or, in other words, when it “goes out of scope”.
- The memory is used for the object “m” on the stack will be removed once the function is done running.
- If we want to create an object on the heap inside a function, then this is what the code would look like:
Heap and Stack Memory explanation with Java Program
- As soon as we run the program, it loads all the Runtime classes into the Heap space.
- When Class JavaHeapStack is loaded Static and Instance variables are created in Heap Memory.
- When main() method is found at Line a, Java Runtime creates stack memory to be used by main() method thread.
- We are creating a primitive local variable at Line b, so it’s created and stored in the stack memory of main() method.
- Since we are creating an Object using a new keyword in Line c, it’s created in Heap memory and stack memory contains the reference for it.
- A similar process occurs when we createJavaHeapStack object in Line d.
- Now when we call callData() method in Line e, a block in the top of the stack is created to be used by callData() method.
- Since Java is pass by value, a new reference to Object is created in the callData() stack block in Line f.
- A string is created in Line g, it goes in the String Pool in the heap space and a reference is created in the callData() stack space for it.
- callData() method is terminated in line h, at this time memory block allocated for callData() in stack becomes free.
- In line i, main() method terminates and the stack memory created for main() method is destroyed.
- Also the program ends at this line, hence Java Runtime frees all the memory and end the execution of the program.