Variables, Objects and References, we frequently listen to these terms while development but usually gets confused between them.
Let’s try to understand a very basic definition along with an example for all three. The concept is similar in any object-oriented programming language but for reference, I’ll be using Java examples. Feel free to comment below if you need examples in any specific language.
Variables
Variables are named storage of any primitive data type.
Name storage means we (developers) define the name of the variable.
Primitive data types are something which predefined in any language like int, float, boolean etc.
Keep in mind Int with the capital I
or Float with the capital F
are non-primitive
data types.
The size of the variable depends on the type of it.
In Java, a char
takes 2 bytes, int
takes 4 bytes, float
takes 8 bytes and so on.
int age = 5;
float pi = 3.14;
Objects
Objects are variables of non-primitive data types or user-defined classes.
An object can’t exist without its class.
It is created by the new
keyword which calls the constructor of that class which ultimately assigns some memory to that object.
Its size depends on the properties defined in that class.
In java, an object is created on the heap.
Employee emp = new Employee();
Here an object of Employee
will be created by calling the new
keyword. Keep in mind that technically emp
is not an object, its just a reference pointing to the object which is created on heap.
Read Refrence below to understand it better.
Reference
A reference is nothing but a pointer pointing to the object. In other words, it is holding the memory address of the object created by new
keyword.
Employee emp = new Employee();
In the same above example, emp
is a reference to the object which is created using the new
keyword.
Basic differences between Variable, Object and Reference
- You can’t create a variable using the
new
keyword. - Variables can’t hold
null
values as primitive data types doesn’t allow that. - If you just write
new Employee();
it will call the constructor and will even assign the memory in heap to that object but there is no reference so you can’t access it. - Chaining is possible in references using the dot(
.
) is most of the languages. you can call a function using object reference followed by a dot(.
) - If you assign once reference to another like
Employee emp2 = emp;
it just copies the reference and but internally both the references are pointing to the same object.