I was thinking about string in java. String are immutable. But when the code is mutable
String str = new String("abc");
System.out.println(str.toUpperCase());
System.out.println(str);
The outout is
ABC
abc
Actually the output should be
ABC
ABC
because String are immutable. Please explain. Thanks!
No, the output is what it is precisely because strings are immutable. Calling toUpperCase()
doesn't change the contents of the existing string, it creates a new one and returns a reference to that... it has to do that, due to strings being immutable.
This isn't just the case for toUpperCase()
- all methods on String
that sound like they might modify the string (e.g. trim()
) actually return a new one instead.
Compare that with the mutable class StringBuilder
, where the object is modified, and a reference to this
is returned:
public class Test {
public static void main(String[] args) throws Exception {
StringBuilder builder = new StringBuilder("abc");
System.out.println(builder); // abc
System.out.println(builder.append("def")); // abcdef
System.out.println(builder); // abcdef
}
}
See more on this question at Stackoverflow