Reference Data Types in JavaJava 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 TypesThere are the following five types of reference types in Java:
Reference vs Primitive Data Types
Memory Allocation and Garbage CollectionIn 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 TypeThe conversion of primitive type to reference type is called autoboxing and the conversion of reference type to primitive type is called unboxing. Comparing Reference TypeWe can also compare the reference types in Java. Java provides two ways to compare reference types: By using the equal (==) operatorIt 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() MethodThe 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 TypeThere 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. Next TopicCounter variable in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India