What is the difference between “text” and new String(“text”)?

后端 未结 12 1144
悲&欢浪女
悲&欢浪女 2020-11-21 04:42

What is the difference between these two following statements?

String s = \"text\";

String s = new String(\"text\");
12条回答
  •  情深已故
    2020-11-21 05:20

    One creates a String in the String Constant Pool

    String s = "text";
    

    the other one creates a string in the constant pool ("text") and another string in normal heap space (s). Both strings will have the same value, that of "text".

    String s = new String("text");
    

    s is then lost (eligible for GC) if later unused.

    String literals on the other hand are reused. If you use "text" in multiple places of your class it will in fact be one and only one String (i.e. multiple references to the same string in the pool).

提交回复
热议问题