Scientech Easy Life Cycle of object in Java | Scientech Easy

Friday, August 3, 2018

Life Cycle of object in Java

In this tutorial, we will discuss a very interesting topic 'the life of an object'. we should know how objects are born, live their life and then die. This topic is known as the Life Cycle of an object in Java. Let's see step by step in an easy way.

Life Cycle of object

Life cycle of object in Java, Object life cycle in Java
Life cycle of object

Step1 :
As you know that Java programs run on the Java virtual machine(JVM). When we compile Java class, it is transformed into bytecode which is platform and machine independent. The compiled classes are stored as a .class file on a disk.
Step 2:
After that, the Java runtime finds out the class on the disk in the form of a .class file. Java classloader loads that class into memory and then  Java runtime reads it into the memory.
Step 3:
Now, Java looks for all initialized static members of the class such as static method, static field, static block. You always remember that all the static members of the class do not belong to any particular instance of the class. It belongs to the class itself and is shared by all the objects created from the class. 
Step 4: A class can be initialized in two ways in Java. First, When you access a static field or static method of the class. For example, when you run the main method in the class, the class is initialized because the main method is static and the second way is when object/instance of the class is created using the new keyword, the class is initialized. 
Step 5:
Now, Java allocates the memory on the heap for the object and memory on the stack for object reference variable.
Step 6:
After allocating the memory, JVM calls the constructor of the class which is like a method but it is called only once when the object is created. Thus, the object lives its life and providing the access to its fields and methods whatever we want and need to access them.
Step 7:
When the accessing of field and methods are completed, the object and its reference are removed from the memory by the JVM. At this time the object has died. You don't have to destroy objects yourself. Actually, when the object is no longer in use, Java runtime calls the garbage collector to destroy all the objects. Hence, objects are born, live and die.

Final words:
I hope that this tutorial will be helpful to understand the object life cycle in Java. We have covered all the points in step by step so that you don't get any problem to understand them. In the next tutorial, we will learn data types in Java. 

Next Data types in Java