What is the difference between Object and Reference variable?


Consider the below example

Student stu = new Student()

Here Student is a Class.

We are creating an object of class Student using new keyword new Student() will create an object of type student and allocate memory in the heap for created object.

This will return the memory address that will be stored inside the variable stu. So stu is a reference variable of Type Student which is storing the address of object created in the heap. Stu is pointing to the object in the heap.

Object vs Reference variable

Multiple reference variable can points to same object. Consider below example

Student stu1 = new Student();
Student stu2 = stu1;

In the above exapmple stu1 and stu2 are 2 reference variable of type Student, which are pointing to the same object in the heap.

Share this thread


comments powered by Disqus


Social Media