OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 3 : Assigning One Object to Another
Unit - 2
Topic 3 : Assigning One Object to Another in Java
In Java, when you assign one object reference to another, you are not creating a new object. Instead, both references will point to the same object in memory.
How It Works
Example:
At this point:
-
No new object is created when assigning
b1
tob2
. -
Both
b1
andb2
refer to the same memory location. -
Any changes made through
b1
will also be visible when accessing throughb2
(and vice versa).
Visualization in Memory
Example Program
Sample Output
Key Takeaways
-
Object variables in Java hold references, not actual object data.
-
Assigning one reference to another makes them point to the same object.
-
Any changes via one reference affect the same underlying object.
-
To make an actual copy, you need to create a new object and copy the values manually (or use cloning).
Comments
Post a Comment