0

Could you please explain to me why the following occors. What is this phenomena called so I can look it up further Thank you:

Date d1=new Date();
Date d2=d1;
d1.setTime(d1.getTime()+60*60*1000);    // Changing d1 will automatically change d2. And visa versa.
System.out.println(d2);
System.out.println(d1);

int number1=7;
int number2=number1;
number1++;
System.out.println(number1+" "+number2); // Only number one is changed.

String str1="hiiiiii";
String str2=str1;
str1="hello";
System.out.println(str1+" "+str2);      //Only str1 is changed.

Many thanks

3 Answers 3

1

First Case: since d1 and d2 are object references and its referring to the same object, Changing d1 will automatically change d2.

Second case: number1 and number2 are primitive types. So it will copy the value of number1 to number2. So only number one is changed

Third case: Though str1 and str2 are both objects and till second line both are referring to the same objects, in the third line you are re-assigning the value str1. So it will create a new object in pool which str1 will refer to.

Sign up to request clarification or add additional context in comments.

Comments

0

Immutable objects or immutability in object oriented programming

Comments

0

Well, if you have one "parent" object, in this case d1 for example, and assign d2 as "child" object of d1, all you do is telling the JVM that d2 IS d1. At that point, JVM does not distinguish between D1 and D2, so any change to D2 also applies to D1.

But in your third example, you do the same thing, but when you change str11, which is a "parent" object, the JVM does not reflect the change on str22, because you did not tell it to do so and the reference to str1 is the original reference that does not reflect on str2. So str1 and 2 become two different object. But if you again changed str2, it would reflect on both.

Comments

Your Answer

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