Java String variable setting – reference or value?

java Strings are immutable, so your reassignment actually causes your variable to point to a new instance of String rather than changing the value of the String.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

on line 2, s1 == s2 AND s1.equals(s2). After your concatenation on line 3, s1 now references a different instance with the immutable value of “abc”, so neither s1==s2 nor s1.equals(s2).

Leave a Comment