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?

2 Answers

9
Gautam On Best Solutions

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

0
markspace On

See if the following makes any more sense to you.

int box1 = 1;
int box2 = 2;
int box3 = 3;

box1 = box2;
box2 = box3;

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

box1 prints "2" and box2 prints "3". This is exactly the same way copying references works, and it'll always have the same pattern.