What does a reference point to when it is declared to be equal to another reference? Begginer Reference Semantics

Viewed 22

I am a new programmer, and I am trying to understand reference semantics in Java. I have some questions about the following code below...

public class Library {
     public void checkOut(Book b) {      
         … 
         //assume that field of b is changed that          
         //shows book is checked out
    }
    public static void main(String [] args) {
         Book b1 = new Book(…);
         Book b2 = new Book(…);
         Book b3 = b2;
         b3.setName(“Inferno”);
         Library l = new Library();
         l.checkOut(b2); 
         if (b3.isCheckedOut()) {
               …
         } else { 
               … 
         }
    } 
}

I understand that the first two lines in the main method construct book references and book objects, and the newly created objects are stored in the reference variables.

My question is how does the third line of the main method work? Is it that the new reference b3 is created and points to the b2 reference that points to the second book object in memory? Or is it that the b3 reference that is created will point directly to the second book object in memory?

When the fourth line of the main method is executed, is it that the book object in memory is changed, and that change will be reflected when either b2 or b3 is called again?

1 Answers

I understand that the first two lines in the main method construct book references and book objects, and the newly created objects are stored in the reference variables.

Not the objects themselves, references to the objects are stored in the reference variables.

Or is it that the b3 reference that is created will point directly to the second book object in memory?

Yes, the b2 reference is copied to the b3 reference and now b3 references the same object.

When the fourth line of the main method is executed, is it that the book object in memory is changed, and that change will be reflected when either b2 or b3 is called again?

Yes.

Related