Object lifetime means how long an object exists in a program. It helps us understand when an object is created and when it is removed.
Object lifetime in Java
// Object is created when you use 'new' ClassName obj = new ClassName(); // Object is destroyed when no references point to it and garbage collector runs
Objects are created using the new keyword.
Java automatically removes objects when they are no longer used, called garbage collection.
MyClass and stores it in obj.MyClass obj = new MyClass();obj = null;localObj is created when the method runs and disappears when the method ends.public void method() { MyClass localObj = new MyClass(); // localObj exists only inside this method }
This program creates two objects. One is set to null right after creation, so it can be removed by Java's garbage collector. The other exists until the program ends. The finalize method shows when objects are destroyed (note: it may run later or not at all immediately).
class ObjectLifetimeDemo { public static void main(String[] args) { MyClass obj1 = new MyClass(); obj1 = null; // obj1 no longer points to the object MyClass obj2 = new MyClass(); // obj2 exists until main ends System.out.println("Program finished"); } } class MyClass { public MyClass() { System.out.println("Object created"); } @Override protected void finalize() throws Throwable { System.out.println("Object destroyed"); super.finalize(); } }
Java's garbage collector decides when to remove objects; it is not immediate after setting references to null.
The finalize method is called before an object is removed but is not guaranteed to run immediately.
Local objects inside methods exist only while the method runs.
Objects are created with new and exist while referenced.
When no references point to an object, Java can remove it automatically.
Understanding object lifetime helps manage memory and avoid errors.
