Java immutable strings confusion

后端 未结 8 1326
粉色の甜心
粉色の甜心 2021-01-13 03:07

If Strings are immutable in Java, then how can we write as:

String s = new String();
s = s + \"abc\";
8条回答
  •  失恋的感觉
    2021-01-13 03:28

    The first answer is absolutely correct. You should mark it as answered.

    s = s+"abc" does not append to the s object. it creates a new string that contains the characters from the s object (of which there are none) and "abc".

    if string were mutable. it would have methods like append() and other such mutating methods that are on StringBuilder and StringBuffer.

    Effective Java by Josh Bloch has excellent discussion on immutable objects and their value.

提交回复
热议问题