Java immutable strings confusion

后端 未结 8 1384
粉色の甜心
粉色の甜心 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:42

    Just to clarify, when you say s = s+"abc"; That means, create a new String instance (which is composed of s and "abc") then assign that new String instance to s. So the new reference in s is different from the old.

    Remember, a variable is effectively a reference to an object at some specific memory location. The object at that location stays at that location, even if you change the variable to refer to a new object at a different location.

提交回复
热议问题