Reference Variable in Java

A reference variable in Java is a variable that holds the memory address (or reference) of an object rather than the object itself. When you create an object in Java, the object is stored in the heap memory, and the reference variable holds the reference to that object. In other words, the reference variable points to that memory location.

For example, consider the following below code:

String str = new String("Hello, World!");

In the above example, str is a reference variable of type String that points to a String object containing the text “Hello, World!”. The actual object is stored in the heap memory, while str holds the reference (i.e. address of the memory location) to that object.

Reference variable in Java.

Declaration and Initialization of Reference Variable in Java

A reference variable in Java is declared using a class type, meaning it can store a reference to an object of that class. To create a reference variable, you need to declare it with a specific type and then assign it to an object. The type of the reference variable must match the type of the object it refers to. The general syntax to create a reference variable in Java is as follows:

ClassName referenceVariable;

For example:

String str; // Declares a reference variable of type String.

Assigning a Reference

You must assign the reference variable to an object before using it. For example:

// Create a String object and assign its reference to the variable.
str = new String("Hello, InfitechX!");

Here, we have created a new String object and assigned it to a reference variable named str. The reference variable str stores the address of memory location to that object. We can also declare and assign in one line also like this:

String str = new String("Hello, InfitechX!");

Another example:

// Declaration and initialization in one line.
String greeting = new String("Good Morning!");

In both examples, str and greeting are reference variables that point to String objects.

Null Reference

You can assign a special value called null to a reference variable, which means that it does not point to any object. Attempting to access a method or field on a null reference will result in a NullPointerException. Look at the below an example.

String name = null;
System.out.println(name); // Output: null

Another example:

String str = null;
System.out.println(str.length()); // This will throw a NullPointerException.

You should check for null before accessing an object’s methods or fields to avoid runtime exceptions.

Types of Reference Variables in Java

There are four types of reference variables in Java. They are as:

  • Strong reference
  • Weak reference
  • Soft reference
  • Phantom reference

Let’s understand one by one with the help of examples.

Strong Reference

A strong reference in Java is a default type of reference that prevents the object it refers to from being garbage collected. The strong reference is accessible as long as there is at least one strong reference pointing to the object.

When you create an object in Java, the reference variable you use to point to that object is a strong reference by default. The object will not be garbage collected until there is at least one strong reference pointing to that object.

Strong references are the most common type of reference used in everyday Java programming to ensure that objects remain in memory as long as they are needed.

Example of Strong reference:

public class StrongReferenceExample {
	public static void main(String[] args) {
     // Create a strong reference pointing to a new object.
        String strongRef = new String("This is a strong reference.");

     // The object is not eligible for garbage collection.
        System.out.println(strongRef);

     // Set the strong reference to null.
        strongRef = null;

      // Now, the object is eligible for garbage collection
      // because there are no more strong references to it
    }
}
Output:
     This is a strong reference.

In this example, strongRef is a strong reference pointing to a String object. As long as strongRef points to the object, the object will not be garbage collected. When strongRef is set to null, the object has no longer any strong references, making it eligible for garbage collection.

Weak Reference

A weak reference is a type of reference in Java that allows the object to be garbage collected when there is no strong reference pointing to it. An object with only weak reference is eligible for garbage collection, even if the weak reference itself is still accessible.

A weak reference is implemented using the java.lang.ref.WeakReference class. Weak reference is often used in scenarios where you want to hold a reference to an object but you don’t want to prevent it from being garbage collected if memory is needed elsewhere.

Example of Weak Reference:

import java.lang.ref.WeakReference;
public class WeakReferenceExample {
 public static void main(String[] args) {
// Create a strong reference pointing to an object.
   String strongRef = new String("This is a strong reference.");

// Create weak reference to the same object.
   WeakReference<String> weakRef = new WeakReference<>(strongRef);

// Accessing the object using the weak reference.
   System.out.println("Weak Reference before GC: " + weakRef.get());

// Set the strong reference to null.
   strongRef = null;

// Suggest JVM to run garbage collection.
   System.gc();

// Access the object using the weak reference after GC.
   System.out.println("Weak Reference after GC: " + weakRef.get());
  }
}
Output:
     Weak Reference before GC: This is a strong reference.
     Weak Reference after GC: null

In this example, Initially, strongRef is a strong reference that is pointing to a String object, so the object is not eligible for garbage collection.

After that, we have created weak reference to the same object. As long as strongRef exists, the object is not garbage collected. When strongRef is set to null, the object is no longer due to not pointing to any strong references.

After calling System.gc(), the object is garbage collected because it only has a weak reference. The weakRef.get() method returns null after garbage collection.

Soft Reference

In Java, a soft reference is a type of reference that is slightly stronger than a weak reference but still allows the object to be garbage collected when JVM is running low on memory. Soft references are created using the java.lang.ref.SoftReference class.

An object with a soft reference is retained in memory as long as there is enough memory available. When the JVM detects that it is running low on memory, it clears soft references to free up space.

The garbage collector prioritizes reclaiming reachable objects over strongly reachable objects but it does so only when necessary. Soft references are commonly used for caching mechanisms where you want to keep objects in memory as long as possible but don’t want to cause OutOfMemoryError.

Example of Soft Reference:

import java.lang.ref.SoftReference;
public class SoftReferenceExample {
public static void main(String[] args) {
 // Create a strong reference pointing to an object.
    String strongRef = new String("This is a strong reference.");

 // Create a soft reference to the same object.
    SoftReference<String> softRef = new SoftReference<>(strongRef);

 // Accessing the object using the soft reference.
    System.out.println("Soft Reference before GC: " + softRef.get());

 // Set the strong reference to null.
    strongRef = null;

 // Suggest JVM to run garbage collection.
    System.gc();

 // Accessing the object using the soft reference after GC.
    System.out.println("Soft Reference after GC: " + softRef.get());
  }
}
Output:
     Soft Reference before GC: This is a strong reference.
     Soft Reference after GC: This is a strong reference.

In this example, initially, the strong reference strongRef is pointing to a String object, so the object is not eligible for garbage collection. The soft reference softRef is also pointing to the same object. Therefore, the object will not be garbage collected as long as there is enough memory.

When we have set strongRef to null, the object no longer has any strong references. After calling System.gc(), the object may or may not be garbage collected, depending on the JVM’s memory usage. If the JVM is running low on memory, the soft reference will be cleared.

Phantom Reference

A Phantom Reference in Java is a special type of reference that allows you to perform cleanup actions (like closing resources) before an object is fully removed from memory. This is useful when you need to release resources such as closing file streams or cleaning up native resources before an object is garbage collected.

Phantom references must be associated with a ReferenceQueue, which receives a notification when the object is ready for garbage collection.

Example of phantom reference:

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
public class PhantomReferenceExample {
public static void main(String[] args) throws InterruptedException {
 // Create a phantom reference pointing to an object.
    String phantomObject = new String("Phantom Reference Example");
        
 // Create a ReferenceQueue object.
    ReferenceQueue<String> refQueue = new ReferenceQueue<>();

 // Create a PhantomReference associated with the object and reference queue.
    PhantomReference<String> phantomRef = new PhantomReference<>(phantomObject, refQueue);

 // Remove strong reference.
    phantomObject = null;

 // Force garbage collection.
    System.gc();

 // Wait to ensure GC has run.
    Thread.sleep(1000);

 // Check if the object is enqueued.
    Reference<?> ref = refQueue.poll();
    if (ref != null) {
       System.out.println("Phantom reference object is ready for garbage collection.");
    } else {
        System.out.println("Phantom reference object is still in memory.");
     }
  }
}
Output:
      Phantom reference object is ready for garbage collection.

Passing Reference Variables to Methods in Java

When you pass a reference variable to a method in Java, you are passing a copy of the reference, not the actual object. This means that changes made to the object’s field inside the method will affect the original object because both the original and the copied reference point to the same object in memory.

However, reassigning the reference variable inside the method will not affect the original reference outside the method because the copied reference is modified, not the original one.

Example:

class Test {
    int value;
}
public class ReferenceExample {
  static void modifyObject(Test obj) {
   // Changing the object's field affects original object. 	
      obj.value = 10;  
  }
  static void reassignReference(Test obj) {
  // Reassigning reference does not affect original reference. 	
     obj = new Test();  
     obj.value = 20;  // Only affects the new object, not the original.
  }
  public static void main(String[] args) {
     Test t = new Test();
     t.value = 5;

     modifyObject(t);
     System.out.println("After modifyObject: " + t.value); 

     reassignReference(t);
     System.out.println("After reassignReference: " + t.value); 
  }
}
Output:
     After modifyObject: 10
     After reassignReference: 10

Reference Variable and Object Lifecycle in Java

The lifecycle of an object in Java is managed by reference variables. An object is eligible for garbage collection when there are no more reference variables pointing to it. For example:

public class Main {
public static void main(String[] args) {
    String str1 = new String("Hello");
    String str2 = str1; // Both str1 and str2 point to the same object.

    str1 = null; // Now str1 is not pointing to the object.
 // The object is still referenced by str2, so it is not eligible for garbage collection.
     str2 = null; // Now, the object is eligible for garbage collection
  }
}

In this example, the String object becomes eligible for garbage collection only after both reference variables named str1 and str2 are set to null.

In this tutorial, we have explained reference variable in Java with the help of some important examples. Reference variable is a fundamental concept in Java that you must understand it. I hope that you will have understood this simple topic and enjoy Java coding!!!

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *