.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.