Java immutable strings confusion

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

       String s = new String();  
    

    Creates a new, immutable, empty string, variable "s" references it.

       s = s+"abc";              
    

    Creates a new, immutable, string; the concatenation of the empty string and "abc", variable "s" now references this new object.

提交回复
热议问题