Object references and assignment

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

I have seen many people getting misunderstood by java object references and their assignment. A common misconception is that whenever a reference variable is assigned another reference variable, it creates a new object. For example, suppose we have a Book class and we are trying to create its object.

 

Here the conception is two objects are created. But this is plain wrong. Only one object is created and two variables refer to it. Let us first understand what exactly happens when the statement Book someBook = new Book();  is executed.

 

  1. Book someBook  creates a reference variable called someBook of type Book .
  2. new Book() actually creates the instance of the class.

So the whole statement Book someBook = new Book(); actually means:
A new instance of class Book is created and it is assigned to the reference variable someBook of type Book.

This can be diagrammatically represented as follows.

BookCreatedAndAssigned
The newly created Book object is referred by variable someBook.

Now the statement Book anotherBook = someBook does not create a new object. It just means “The object that is being referred by the variable someBook is also referred by this new reference variable anotherBook “.

This can be seen diagrammatically as follows.

Now two reference variables are referring to the same Book object
Now two reference variables are referring to the same Book object

Hope this article helps clear this common doubt.

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

5 thoughts on “Object references and assignment

Leave a Reply

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