I am confuse about String and String Builder. Here is my simple code
StringBuilder sb1 = new StringBuilder("123");
String s1 = "123";
sb1.append("abc");
s1.concat("abc");
System.out.println(sb1 + " " + s1);
sb1 output for 123abc. It is ok! because it use append method.But String s1 should be abc123 but it output is abc. Why? And what is concat method purpose? Please explain me.
Thank you
.But String s1 should be abc123 but it output is abc.
Strings are immutable in Java. concat
doesn't change the existing string - it returns a new string. So if you use:
String result = s1.concat("abc");
then that will be "123abc" - but s1
will still be "123". (Or rather, the value of s1
will still be a reference to a string with contents "123".)
The same is true for any other methods on String
which you might expect to change the contents, e.g. replace
and toLowerCase
. When you call a method on string but don't use the result (as is the case here), that's pretty much always a bug.
The fact that strings are immutable is the whole reason for StringBuilder
existing in the first place.
See more on this question at Stackoverflow