assignment-object-java

Here in this post, we are going to see how object reference variable takes place when assigning to another object reference.

In java when we assign an object reference variable to another, we are only creating a copy of the object reference variable, not a copy of the object.

What do you think the above code snippet does? You might think that we are assigning a copy of the object referred to by s1, to the object reference variable s2. So you might think that s1 and s2 are currently referring to two different objects. But this is not the case.

object-reference

Always remember, when you are assigning an object reference variable to another object reference variable, you are not creating a copy of the object. You are only creating a copy of the reference variable which points to the same object. For better understanding see the below example.

Here s1 is the reference variable which is referring to the Student object. In the second line, we are assigning s1 to s2. Now s1 and s2 both referring to the same object.

object-reference-assigning

Now if we change anything to the Student object through s2, it will be reflected to the object which s1 is referring. Because both the reference variables are referring to the same object.

Another thing to remember is that both these reference variables are not linked to each other in any other way. They are only referring to the same objects. For clear understanding see the below example:

If we set s1=null or s2=null, this will not effect the other reference variable or the object. So if we set s1=null, it will only unhook the s1 reference variable from the Student object. This will not effect the s2 variable or the Student object.

object-assignment-java

Points:

  1. When we are assigning an object reference variable to another, we are creating a copy of the reference variable, not the object.
  2. Both the reference variables points to the same object.
  3. Any changes made to the object through one reference variable will effect the object which is referred by another reference variable.
  4. Both reference variables are not linked in any other way, they are only referring to the same object.
  5. If we set a reference variable to null, it will only unhook that reference variable from the object. It will not effect the other one.
Assigning object reference variable to another in Java
Tagged on:

One thought on “Assigning object reference variable to another in Java

  • October 4, 2016 at 4:40 am
    Permalink

    Very well explained

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *