VOOZH about

URL: https://www.geeksforgeeks.org/java/types-references-java/

โ‡ฑ Types of References in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Types of References in Java

Last Updated : 7 Aug, 2025

One of the important parts of memory management in Java is, how it handles references to objects and decides when to remove those objects that are no longer needed. Java offers several types of references, and it is important to understand that all references are not the same.

Java References Types

In Java, there are four types of references differentiated by the way in which they are garbage collected.

  • Strong References
  • Weak References
  • Soft References
  • Phantom References

Prerequisite: Basic understanding of Garbage Collection

1. Strong References

This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null.

MyClass obj = new MyClass ();

Here 'obj' object is strong reference to newly created instance of MyClass, currently obj is active object so can't be garbage collected.

obj = null; //'obj' object is no longer referencing to the instance. So the 'MyClass type object is now available for garbage collection.

๐Ÿ‘ Strong References in Java

Example:


2. Weak References

 Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. ๐Ÿ‘ weak-references-in-java

Example:


Output
GeeksforGeeks
GeeksforGeeks

Note: The object may be garbage collected anytime after the strong reference is removed.

3. Soft References

In Soft reference, even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory.To create such references java.lang.ref.SoftReference class is used. ๐Ÿ‘ soft-references-in-java

Example:


Output
GeeksforGeeks
GeeksforGeeks


4. Phantom References

The objects which are being referenced by phantom references are eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called โ€˜reference queueโ€™ . They are put in a reference queue after calling finalize() method on them.To create such references java.lang.ref.PhantomReference class is used.

Example:

Comment
Article Tags:
Article Tags: