Example 1 :
Example 2 :
public class Memory { public static void main(String[] args) { // Line 1 int i=1; // Line 2 Object obj = new Object(); // Line 3 Memory mem = new Memory(); // Line 4 mem.foo(obj); // Line 5 } // Line 9 private void foo(Object param) { // Line 6 String str = param.toString(); //// Line 7 System.out.println(str); } // Line 8 }
Following is the Java Runtime Memory
Following are the steps :
- When java <class file name> is executed on a operating system, then the JRE installed on that operating system is activated.
- JVM instance is created by the JRE in the ram for each java <class file name> execution
- JVM instance creates
- Class Area(Method Area)
- Heap
- Stack
- PC Register
- Native Method Stack
- JVM loads all the classes and jars rt.jar, $JAVA_HOME/jre/lib/ext directory jars and classpath files or -cp path
- These classes are loaded in Method Area
- Main thread is the 1st thread is called for which a stack is created.
- Main method is the first method for the main thread for which a frame is created in Stack.
- Line 2 : Local variable i is created in stack frame.
- Line 3 : Object obj is created in heap and its reference is stored in stack
- Line 4 : Similarly object mem is created in heap and its reference is stored in stack
- Line 5 : Method foo is called for which a new frame is created in stack
- Line 6, Line 7 : The variable param, str is created in the new frame in stack
- Line 8 : The frame created for method foo is destroyed.
- Line 9 : The method execution of main is completed and its last frame is destroyed on main thread stack
- Line 10 : Since the main method execution is completed main stack is destroyed.
- Object obj and mem is unreference, it reference does not exist in any stack for they become eligible for garbage collected.
Reference :