0
0
Javaprogramming~15 mins

Object lifetime in Java

Choose your learning style8 modes available
menu_bookIntroduction

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.

When you want to know how long your data stays in memory.
When you want to manage resources like files or connections safely.
When you want to avoid using objects that no longer exist.
When debugging to find why some objects disappear or stay too long.
regular_expressionSyntax
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.

emoji_objectsExamples
line_end_arrow_notchThis creates a new object of MyClass and stores it in obj.
Java
MyClass obj = new MyClass();
line_end_arrow_notchThis removes the reference to the object, so it can be removed by the garbage collector if no other references exist.
Java
obj = null;
line_end_arrow_notchHere, localObj is created when the method runs and disappears when the method ends.
Java
public void method() {
    MyClass localObj = new MyClass();
    // localObj exists only inside this method
}
code_blocksSample Program

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).

Java
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();
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Java's garbage collector decides when to remove objects; it is not immediate after setting references to null.

line_end_arrow_notch

The finalize method is called before an object is removed but is not guaranteed to run immediately.

line_end_arrow_notch

Local objects inside methods exist only while the method runs.

list_alt_checkSummary

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.