Understanding the object lifecycle helps you know how objects are created, used, and removed in a program.
0
0
Object lifecycle in Java
Introduction
When you want to create a new object to store data or behavior.
When you need to know how long an object stays in memory.
When you want to clean up resources used by an object.
When debugging to see when objects are created or destroyed.
When managing memory efficiently in your program.
Syntax
Java
ClassName obj = new ClassName(); // use obj obj = null; // object eligible for garbage collection
Objects are created using the new keyword.
Objects are removed automatically by Java's garbage collector when no longer used.
Examples
This creates a new
Car object and stores it in myCar.Java
Car myCar = new Car();This removes the reference to the
Car object, making it ready for cleanup.Java
myCar = null;This example shows creation and hints at destruction using
finalize() and garbage collection.Java
public class Person { public Person() { System.out.println("Person created"); } @Override protected void finalize() throws Throwable { System.out.println("Person destroyed"); super.finalize(); } } Person p = new Person(); p = null; System.gc();
Sample Program
This program creates an object, removes its reference, and calls garbage collection to show when the object is destroyed.
Java
public class ObjectLifecycleDemo { static class Demo { Demo() { System.out.println("Object created"); } @Override protected void finalize() throws Throwable { System.out.println("Object destroyed"); super.finalize(); } } public static void main(String[] args) { Demo obj = new Demo(); obj = null; // Remove reference System.gc(); // Suggest garbage collection try { Thread.sleep(1000); // Wait to see finalize output } catch (InterruptedException e) { e.printStackTrace(); } } }
OutputSuccess
Important Notes
Garbage collection runs automatically but calling System.gc() only suggests it; it may not run immediately.
The finalize() method is called before an object is removed but is deprecated in newer Java versions.
Setting object references to null helps the garbage collector know the object is no longer needed.
Summary
Objects are created with new and live while referenced.
When no references remain, objects become eligible for garbage collection.
Java automatically cleans up unused objects to free memory.