[java.lang.ref](<https://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html>) package provides reference-object classes, which support a limited degree of interaction with the garbage collector.

Java has four main different reference types. They are:

1. Strong Reference

This is the usual form of creating objects.

MyObject myObject = new MyObject();

The variable holder is holding a strong reference to the object created. As long as this variable is live and holds this value, the MyObject instance will not be collected by the garbage collector.

2. Weak Reference

When you do not want to keep an object longer, and you need to clear/free the memory allocated for an object as soon as possible, this is the way to do so.

WeakReference myObjectRef = new WeakReference(MyObject);

Simply, a weak reference is a reference that isn’t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself.

When you need the object you created, just use .get() method:

myObjectRef.get();

Following code will exemplify this:

WeakReference myObjectRef = new WeakReference(MyObject);
System.out.println(myObjectRef.get()); // This will print the object reference address
System.gc();
System.out.println(myObjectRef.get()); // This will print 'null' if the GC cleaned up the object

3. Soft Reference

Soft references are slightly stronger than weak references. You can create a soft referenced object as following: