Tutorials/Java/java.lang package
Lesson

Garbage Collection

java.lang package/Java

♻️ Garbage Collection

🔹 Introduction

Garbage Collection (GC) in Java is an automatic memory management process handled by the JVM.

It finds and removes unused objects from heap memory so developers don’t need to free memory manually.

🔹 Why Garbage Collection is Needed?

  • Prevents memory leaks

  • Frees unused heap memory

  • Improves application performance

  • Avoids manual memory handling (unlike C/C++)

🔹 What is Garbage?

An object becomes garbage when:

  • No reference points to it

  • It’s no longer reachable from the program

🔹 Example

plaintext
Student s = new Student();
s = null; // object becomes eligible for GC

🔹 How Garbage Collection Works

GC works in 3 main steps:

1️⃣ Marking

  • JVM identifies which objects are still in use

  • Unused objects are marked as garbage

2️⃣ Sweeping

  • JVM removes the marked (unused) objects

  • Memory is freed

3️⃣ Compacting

  • Remaining objects are rearranged

  • Prevents memory fragmentation


🔹 When GC Runs?

  • JVM decides automatically

  • Runs when heap memory is low

  • Developer cannot force GC

plaintext
System.gc(); // Request only, not guaranteed

🔹 finalize() Method (Important)

plaintext
protected void finalize() {
   // cleanup code
}

⚠️ Deprecated (avoid using it)


🔹 How to Make Object Eligible for GC

  • Assign null

  • Reassign reference

  • Object inside method ends

  • Circular references without external reference


🔹 Advantages of Garbage Collection

✔ Automatic memory management

✔ Prevents memory leaks

✔ Improves code reliability

✔ No manual free() required


🔹 Interview One-Line Answer

Garbage Collection in Java is an automatic process by JVM to remove unused objects from heap memory to free space and improve performance.

Garbage Collection | Java | Softcrayons Tech Solutions