Java – string as reference type

See English answer > java string variable setting – reference or value? 9

String s1 = "x";
String s2 = s1;
s1 = "xyz";
System.out.println(s2);

It prints "X" instead of "XYZ", even if I change the object referred to in S2 This does not happen when I change an array Why are strings special?

Solution

Because string, like many other types, overrides object Tostring() and returns another string instead of the string returned by the default implementation (of course, it returns itself)

You're confusing "assigning values to variables" and "changing the state of objects" If you use an array to perform the same operation, the same behavior will occur:

char[] s1 = new char[] {'x'};
char[] s2 = s1;
s1 = new char[] {'x','y','z'};
System.out.println(Arrays.toString(s2));

When assigning different arrays to S1, the array pointed to by variable S2 will not be changed

Of course, if S1 and S2 point to the same array and you modify that array, they will all point to the same modified array:

char[] s1 = new char[] {'x'};
char[] s2 = s1;
s1[0] = 'y';
System.out.println(Arrays.toString(s2));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>