Interview Q&A / Java

AdvancedQuick answer1 min readUpdated 3 Oct 2026

What are strong, soft, weak and phantom references in Java?

SHORT ANSWER

A strong reference prevents collection. A soft reference is cleared only when memory is short, a weak reference is cleared at the next collection once no strong refs remain, and a phantom reference is used to know when an object has been reclaimed.

Explain it simply

Strong is holding a book in your hand: nobody takes it. Soft is a book left on the table, which the librarian removes only when shelf space is running out. Weak is a sticky note on the wall, thrown away at the next cleaning. Phantom is a notification that the book has already been taken away.

Example

java
import java.lang.ref.*;
import java.util.*;

Object strong = new Object();                                  // normal reference

SoftReference<byte[]> soft = new SoftReference<>(new byte[1000]);   // cache-like data
WeakReference<Object> weak = new WeakReference<>(new Object());

// after a GC the weak target is typically gone:
// weak.get() may return null (not guaranteed to be immediate)

Map<Object, String> metadata = new WeakHashMap<>();            // entry disappears when the key is unreachable elsewhere

What to say in the interview

"Strong references are the default and keep objects alive. SoftReference suits memory-sensitive caches, since the JVM clears them before throwing OutOfMemoryError. WeakReference does not keep its target alive and underlies WeakHashMap, which is useful for attaching metadata to objects without leaking them. PhantomReference's get always returns null and is used with a ReferenceQueue for cleanup after collection, and has largely taken over from finalize. I always check get() for null before using it."

Common mistakes

  • Using soft references for a production cache without sizing limits.
  • Keeping a strong reference elsewhere and wondering why the weak one never clears.

#java#jvm#references

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.