Search code examples
javavariable-assignmentpass-by-value

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?


Solution

  • 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 . :)