Flow of Code inside JVM

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
	} // Line 8


Following is the Java Runtime Memory

Following are the steps :

  1. When java <class file name> is executed on a operating system, then the JRE installed on that operating system is activated.
  2. JVM instance is created by the JRE in the ram for each java <class file name> execution
  3. JVM instance creates
    1. Class Area(Method Area)
    2. Heap
    3. Stack
    4. PC Register
    5. Native Method Stack
  4. JVM loads all the classes and jars rt.jar, $JAVA_HOME/jre/lib/ext directory jars and classpath files or -cp path
  5. These classes are loaded in Method Area
  6. Main thread is the 1st thread is called for which a stack is created.
  7. Main method is the first method for the main thread for which a frame is created in Stack.
  8. Line 2 : Local variable i is created in stack frame.
  9. Line 3 : Object obj is created in heap and its reference is stored in stack
  10. Line 4 : Similarly object mem is created in heap and its reference is stored in stack
  11. Line 5 : Method foo is called for which a new frame is created in stack
  12. Line 6, Line 7 : The variable param, str is created in the new frame in stack
  13. Line 8 : The frame created for method foo is destroyed.
  14. Line 9 : The method execution of main is completed and its last frame is destroyed on main thread stack
  15. Line 10 : Since the main method execution is completed main stack is destroyed.
  16. Object obj and mem is unreference, it reference does not exist in any stack for they become eligible for garbage collected.

Reference :

Leave a Comment