What is difference between reference and object?

1 answer

Answer

1023199

2026-05-15 20:35

+ Follow

References are stored in stack while objects are stored in heap.

Reference holds the memory address of an object, that's why they are called reference. If they don't refer to any object in heap, they hold 'null', meaning nothing.

Objects hold the actual data in them. This data is accessed (either read, or written) through reference. An object may be referenced by zero or more references.

For example, consider a class Person, which can hold 'name'.

I create 2 reference variables of Person type.

Person p1;

Person p2;

at this moment both references contain 'null'. An attempt to access 'name' data will throw an error. Now assigning new object to 'p1'.

p1 = new Person();

this causes an object to be created in heap, and its reference(memory address) is stored in p1. Now I can access 'name' data of this object created through p1.

p1.name = "Tom";

Assigning p2 to p1, will make p2 pointing the same object in the heap as p1 is pointing to. Thus if you change 'name' through p2, you are actually changing the same object as p1 is pointing to.

p2 = p1;

p2.name = "Sam";

both p1 and p2 reference variables that are in stack, are pointing to the same object that is in heap.

Hope this helps :)

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.