Variables, Objects and References, we frequently listen to these terms while development but usually gets confused between them.
This post was originally posted at https://agrawalsuneet.github.io/blogs/variable-vs-object-vs-reference/ and reposted on Medium on 4th Dec 2020.
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 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 not primitive data types, those 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 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.