0

I know that String is immutable which means once created it cannot change its size (can't become larger or smaller) or it cant be changed any of its characters. Now, I found 2 examples and it is a bit unclear for me.

So in this example the String s will become from "1" -> "123". so it will change its size in the first place, will become larger. But String is immutable, how come that??

 String s = "1";   // s holds "1"
 s += "2";         // s holds "12"
 s +=3;            // s holds "123"

Then I have another example using concat method:

String s1 = "1";
String s2 = s1.concat("2");
s2.concat("3");
System.out.println(s2);

And here the answer is "12" which I undersand because I create a new String object s2 that CAN change its size and concat with s1 and then for S2 concat with s3 wont work.

My question is why in the first example is permited to concat all those values to String s?

Aled
  • 1
  • 1
    Does this answer your question? [Immutability of Strings in Java](https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java) – Peter234 Jul 16 '23 at 11:42

0 Answers0