As developer its important to know how memory works in java, its helps code optimization. Here we will learn how to manage memory in java.
Java memory split in to two section
The stack and the Heap.
Stack is widely used memory, all the primitive types other than String are stored in stack, values stored in stack is not shared across the JVM because every thread have its own stack. Java exactly knows when the data on the stack be destroyed. We all know that stack is First In Last Out, so very time its create a data in a stack it will be the top of the existing data. For example, in below code
int age = 12;
int height = 100;
String name = "User";
Data of the age variable is stored in stack at first on the top, then height variable is created on the stack on top of the age, then the name reference is create in stack on the top of the height variable.
In the above stack image we can see the primitive values are stored in stack, but the String reference only saved in stack, where the data of String is getting saved, yes its getting saved in heap memory.
Heap
Data allowed in heap will be live longer than stack, because there only one heap per application, so the data saved in heap will be shared with other method or function across the application.
Here I add some code snippet for collection object. I am adding list of string in List object, and then printing the string calling other method. Below code up to line number 12, we are adding string in list called stringList.
If you see the above image stringList is out of scope. Because the current thread is running getList() until line 22 execute stringList is out of scope. After Line 22 execute stringList will be on visible, see the below image
Super explanation
ReplyDelete
DeleteThank you for your support!.