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.

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

5 comments for “Object references and assignment

  1. newlearner
    July 25, 2013 at 10:50 pm

    This is useful thanks!

    • Prasad Kharkar
      July 26, 2013 at 8:36 am

      I am glad it was useful for you 🙂

      • Seeta
        May 10, 2015 at 8:56 am

        What about the String class. I assume for String it will create new instance. Please clarify

  2. Abhijit
    May 10, 2016 at 4:10 pm

    nice pos.. very helpful!

Leave a Reply

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