I'm posting here and snap from Book "Java The complete reference". I tried to test the statement made in this snapshot. Result is 20 for both b1 and b2 which shows that objects are linked. But the book says Objects are not linked and any change to b1 should not affect, b2.

Where I am making mistake?

public static void main(String[] args) {
Box b1 = new Box();
b1.width = 10;
b1.height = 20;
b1.depth = 15;

Box b2 = b1;
double vol;
// assign values to mybox1's instance variables

/* assign different values to mybox2's
instance variables */
b1.width = 20;
b1.height = 299;
b1.depth = 15;


enter image description here

  • Some people vote to close this as 'assistance to write or debug code' which IMHO isn't really the case. Only because OP adds a coding example doesn't necessarily make it a coding question. As far as I see it it's more about how references in Java work (which may or may not be off topic, not sure). Aug 8, 2016 at 11:52

1 Answer 1


No, the book does not claim that they are not linked - it says that b1 and b2 are referring o the same object.

It only states that assignment to one of them does not change the other in any way.

You are mutating the Object they both refer to.

  • you see the last line in the snap., if you change b1, it should not affect b2. then why once i have changed b1, b2 has changed too...? and book says that objects are not linked... you can read carefully in snap
    – Roker
    Aug 8, 2016 at 13:35
  • No, the books clearly says that both are pointing to the same object. They are not linked in any other way, but if you modify the object they refer to through any of the two references, you'll see the changes through the other as well.
    – Hulk
    Aug 8, 2016 at 14:14
  • As the image shows, there is only one Object that has width, height and depth. The book just wants to make clear that changing one reference (i.e. assigning a different value to it - e.g. null, or a reference to some other box object) does not change the other reference in any way.
    – Hulk
    Aug 8, 2016 at 14:18
  • 1
    @Roker: my mum calls me "son", my friends call me "Jörg", my hairdresser calls me "Mr. Mittag". If my hairdresser cuts my hair, it doesn't matter what name you use to reference me, my hair is still cut. You won't see me with long hair, just because you refer to me by a different name. Aug 8, 2016 at 21:19
  • Sorry @Jorg it's not just name, it has been clearly mentioned that if you change b1, b1 will change but b2 is still pointing to the original object, and original object has not changed...
    – Roker
    Aug 10, 2016 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.