Object reference variable in Java

In Java, we have two types of variables, the primitive variable and the object reference variable. The primitive we learned in the previous tutorials, in this tutorial I will be with you to learn about the object reference variable and its difference with the primitive variable.

What is the object reference variable?

Objects are instances of a class, which are created using the new operator, for example:

then a heap address in memory containing the data of that object is returned, and the value of this address is assigned to a variable, and this variable is called a reference variable, this object is called: an object is referenced.

We can see the object reference variable as an object management object, which allows us to access the properties of that object.

The default value of the reference variable is null if the variable is not assigned to any address of the object. That means, it is declared as follows:



Difference between primitive and reference variables

The first fundamental difference we can see is that the primitive variable holds a value, while the object reference only stores the address in the memory of the object to which it refers.

For example:

and

– We use the == operator to compare two primitive variables, while the object reference variable must use the equals() method.

– The primitive variable has only eight data types, and the object reference variable is not limited.

– The default value of object reference is always null if it is not set, and the primitive variable can be 0, false, 0.0.

– Object reference variables are not usable with mathematical operators, while primitive variables can be manipulated using them.

– The object reference variable is maintained by the garbage collection, when it is no longer used, it is destroyed by the garbage collection while the primitive variable is not managed by the garbage collection.

Add Comment