I know that array a
and b
are pointing to the same place where as Strings s1
, s2
are not. Why?
Code:
String[] a = {"a","b","c"};
String[] b = a;
a[0] = "Z";
String s1 = "hello";
String s2 = s1;
s1 = "world";
System.out.println(Arrays.toString(a) + " - a"); //a and b are same
System.out.println(Arrays.toString(b) + " - b");
System.out.println(s1 + " "+ s2); // s1 and s2 are not same.
Output:
[Z, b, c] - a
[Z, b, c] - b
world hello
At point (2), s1
and s2
are pointing to the same literal in the pool. But when you change s1
, another literal is created and the strings are not pointing to the same place anymore.
String s1 = "hello";
String s2 = s1; (2)
s1 = "world";
You can validate this by printing the result of
s1 == s2
Note that I didn't use equals
because I'm interested in comparing references. Now as soon as you assign s1
with a different value, things will look like:
+-------+
| world | <- s1
+-------+
+-------+
| hello | <- s2
+-------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With