Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable assignment: why is box1 not updated to box3?

I have a beginners question about java fundamentals of variable assignments.

In my example code I have 3 boxes (Objects). I assign the boxes as follows:

    Box box1 = new Box("Furniture", 1);
    Box box2 = new Box("Games", 2);
    Box box3 = new Box("Cloths", 3);

    box1 = box2;
    box2 = box3;

    System.out.println(box1.toString());
    System.out.println(box2.toString());

Now, I would expect that box1 also points to box3. But it turns out, that it still points to box2, eventhough I also changed the reference of box2 to box3. Why is that so?

like image 685
Phil Avatar asked Mar 08 '26 08:03

Phil


1 Answers

This is your initial state :

     +-----------------+             +----------------+
     |  box1 ( ref )   +------------>|  box1 ( obj )  |
     +-----------------+             +----------------+

     +-----------------+             +----------------+
     |  box2 ( ref )   +------------>|  box2 ( obj )  |
     +-----------------+             +----------------+

     +------------------+            +----------------+
     |  box3 ( ref )    +----------->|  box3 ( obj )  |
     +------------------+            +----------------+

This is what happens after box1 = box2 :

     +-----------------+             +----------------+
     |  box1 ( ref )   +----+        |  box1 ( obj )  |
     +-----------------+    |        +----------------+
                            |
     +-----------------+    +------> +----------------+
     |  box2 ( ref )   +------------>|  box2 ( obj )  |
     +-----------------+             +----------------+

     +------------------+            +----------------+
     |  box3 ( ref )    +----------->|  box3 ( obj )  |
     +------------------+            +----------------+

This is what happens after box2 = box3

     +-----------------+             +----------------+
     |  box1 ( ref )   +----+        |  box1 ( obj )  |
     +-----------------+    |        +----------------+
                            |
     +-----------------+    +------> +----------------+
     |  box2 ( ref )   +----+        |  box2 ( obj )  |
     +-----------------+    |        +----------------+
                            |
     +------------------+   +------->+----------------+
     |  box3 ( ref )    +----------->|  box3 ( obj )  |
     +------------------+            +----------------+

Now you should be able to figure out why the output is like that . :)

like image 55
Gautam Avatar answered Mar 10 '26 15:03

Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!