Right, it's trying to modify the object that s2 is referencing in the 2nd example. My confusion is why the string object referenced by s in the first example can be modified but the string object referenced by s2 in the 2nd example can not be modified.
Cosmid Constantine wrote:Right, it's trying to modify the object that s2 is referencing . . . why the string object referenced by s in the first example can be modified . . . .
No String objects were modified in the making of this motion picture.
String objects cannot be modified by any normal code. You are not modifying any objects. You are creating new String objects, both with + and concat() but those new objects disappear into some sort of cyber‑limbo never to be seen again if they are not used somehow. In the code you showed, there are = operators to use those objects by replacing what s2 points to. Remember the += operator includes =.is equivalent toJLS (=Java® Language Specification) link.
Please use the reply button rather than the quote button.
I finally got it! Because there's a = in all of these, so it's not modifying any of these objects but instead it keeps referencing a newly created object. And there is only one line without the = and that's where it's trying to modify a string object and causes an error. Thank you for your patience to keep explaining it to me!