Reference Data Types in Java
Java provides two types of data types primitive and reference data type. The primitive data types are predefined in Java that serves as a fundamental building block while the reference data type refers to where data is stored.
In this section, we will discuss what is a reference data type in Java, and how they differ from the primitive data type.
In Java, non-primitive data types are known as reference types. In other words, a variable of class type is called reference data type. It contains the address (or reference) of dynamically created objects. For example, if Demo is a class and we have created its object d, then the variable d is known as a reference type.
It refers to objects. It is not pre-defined. It is created by the programmer if required. The reference types hold the references of objects. All reference types are a subclass of type java.lang.Object. It provides access to the objects stored in the memory.
The examples of reference data types are class, interface, String, Arrays, etc.
Java Reference Types
There are the following five types of reference types in Java:
Reference vs Primitive Data Types
Memory Allocation and Garbage Collection
In Java, the new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. Objects occupy memory in the Java heap space. We can also use the new keyword to create the array object.
If there are no references to an object, the memory used by that object can be reclaimed during the garbage collection process.
Conversion Between Primitive Type and Reference Type
Comparing Reference Type
We can also compare the reference types in Java. Java provides two ways to compare reference types:
By using the equal (==) operator
It compares the memory locations of the objects. If the memory address (reference) of both objects is the same, the objects are equal. Note that it does not compare the contents of the object. For example:
By using the String.equals() Method
The method belongs to the String class. It overrides the equals() method of the Object class. It also uses the equal operator (==) for comparing the reference type. For example, consider the following code snippet:
Copying Reference Type
There are two possibilities when we copy reference types, either a copy of the reference to an object is made or an actual copy (creating a new copy) of the object is made.
In the following example, we have assigned a reference to the object. If we made any changes in the object, it will also reflect the reference and vice-versa.