Showing posts with label Object Destruction. Show all posts
Showing posts with label Object Destruction. Show all posts

Saturday, March 21, 2026

What is Object Lifecycle in Java?


The Object Lifecycle in Java refers to the stages an object goes through from:

👉 Creation → Usage → Eligible for Garbage Collection → Destruction


🔍 Stages of Object Lifecycle

1️⃣ Object Creation

An object is created using the new keyword.

class Student {
    String name;
}

Student s = new Student();

👉 Memory is allocated in heap memory, and the constructor is called.


2️⃣ Object Usage

Once created, the object is used by calling methods or accessing variables.

s.name = "John";

👉 Object is actively used by the application.


3️⃣ Object Becomes Eligible for Garbage Collection

An object becomes eligible for GC when it is no longer reachable.

💡 Example:

Student s1 = new Student();
s1 = null;

👉 Now the object has no reference → eligible for GC


4️⃣ Garbage Collection

The JVM automatically removes unused objects using Garbage Collector (GC).

👉 This frees memory and improves performance.


5️⃣ Object Destruction (Finalization)

Before removing the object, JVM may call:

protected void finalize() throws Throwable

⚠️ Note:

  • finalize() is deprecated in modern Java

  • Not guaranteed to execute




🔄 Lifecycle Flow

Object Creation → Object Usage → No References → GC Eligible → Garbage Collection

🧠 Types of Object Eligibility

Objects become eligible for GC in cases like:

  • ✔️ Null reference

  • ✔️ Reassigned reference

  • ✔️ Out of scope

  • ✔️ Anonymous objects


💡 Example with Reassignment

Student s1 = new Student();
Student s2 = new Student();

s1 = s2;

👉 First object becomes eligible for GC


🚀 Why Object Lifecycle is Important?

  • ✔️ Helps in memory management

  • ✔️ Avoids memory leaks

  • ✔️ Improves performance

  • ✔️ Important for real-time applications


🎯 Interview Tip

👉 Common question:
When does an object become eligible for Garbage Collection?

✔️ Answer:
When it is no longer reachable by any active reference.


📚 Learn More Java Internals

Master JVM, memory management, and real-time Java concepts:

👉 https://ashokitech.com/core-java-online-training/



Thread vs Runnable in Java: Key Differences, Best Practices & Which One to Use (2026 Guide)

Multithreading is a core part of Java —but one of the most common interview questions is: Should you use Thread or Runnable ? Thread is a ...