Java immutable strings confusion

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

    String s = new String();
    

    An empty String object ("") is created. And the variable s refers to that object.

    s = s + "abc";
    

    "abc" is a string literal (which is nothing but a String object, which is implicitly created and kept in a pool of strings) so that it can be reused (since strings are immutable and thus are constant). But when you do new String() is totally different because you are explicitly creating the object so does not end up in the pool. You can throw is in the pool by something called interning.

    So, s + "abc" since at this point concatenation of and empty string ("") and "abc" does not really create a new String object because the end result is "abc" which is already in the pool. So, finally the variable s will refer to the literal "abc" in the pool.

提交回复
热议问题