PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Garbage Collection in Java

← All stacks

Theory

122/270

Garbage Collection in Java

Garbage collection frees heap objects that nothing points to anymore. You don’t call free() like C++. The JVM decides when to collect.

System.gc() is only a hint, not a force. Memory leaks still happen if you keep unwanted references (static lists, caches).

Don’t say “Java has no memory problems”. GC helps; leaks are still possible.

Let's take this on the board with one tiny Main class — no extra files. Garbage Collection in Java — output: a is null; GC may collect the unused String. After a = null, no reference remains — GC can free it. Start from main, go line by line, and stop at each print. That output is the proof for Garbage Collection.

Exam tip

GC frees unreachable objects. You cannot force it. Leaks still possible if references remain.

Example

// GC
public class Main {
  public static void main(String[] args) {
    String a = new String("temp");
    a = null;
    System.out.println("a is null; GC may collect the unused String");
    System.gc();
  }
}

Garbage Collection in Java — output: a is null; GC may collect the unused String. After a = null, no reference remains — GC can free it.

Short notes

  • DefGC frees heap objects that nothing points to.
  • RuleYou don’t free() yourself. JVM decides when.
  • RememberSystem.gc() is a hint, not a force.
  • TrapKeeping unwanted references → leak even with GC.

Questions

1

What does GC free?

2

Does System.gc() force GC?

Previous← Performing multiple taskNextRuntime class →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.