Page 1 of 1

[HD Pg 0, Sec. 3.2.1 - reference-variables-and-primitive-variables]

Posted: Sun May 12, 2019 8:48 am
by zeldalex
Hi, I was wondering why str1 is not changed in the following code

Code: Select all

String str1 = new String("String1");
String str2 = str1;
str2 = "String2";
System.out.println(str1);
 
The output will always be String1, changes on str2 seems doesn't affect str1, but according to my understanding, with the 'new' keyword the String object shall be placed on the heap and both str1 and str2 shall point to the same object?

Re: [HD Pg 0, Sec. 3.2.1 - reference-variables-and-primitive-variables]

Posted: Sun May 12, 2019 10:07 am
by admin
Yes, at the end of String str2 = str1; both str1 and str2 will point to the same string object containing "String1".
But the next statement is str2 = "String2"; this will make str2 point another string object containing "String2". But this statement doesn't affect str1. It will still point to the first string object containing "String1".