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

后端 未结 12 1142
悲&欢浪女
悲&欢浪女 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 04:56

    Any String literal gets created inside string literal pool and the pool doesn't allow any duplicates. Thus if two or more string objects are initialized with the same literal value then all objects will point to the same literal.

    String obj1 = "abc";
    String obj2 = "abc";
    

    "obj1" and "obj2" will point to the same string literal and the string literal pool will have only one "abc" literal.

    When we create a String class object using the new keyword the string thus created is stored in heap memory. Any string literal passed as parameter to the constructor of String class however is stored in string pool. If we create multiple objects using the same value with the new operator a new object will be created in the heap each time, because of this new operator should be avoided.

    String obj1 = new String("abc");
    String obj2 = new String("abc");
    

    "obj1" and "obj2" will point to two different objects in the heap and the string literal pool will have only one "abc" literal.

    Also something that is worth noting with regards to the behavior of strings is that any new assignment or concatenation done on string creates a new object in memory.

    String str1 = "abc";
    String str2 = "abc" + "def";
    str1 = "xyz";
    str2 = str1 + "ghi";
    

    Now in the above case:
    Line 1: "abc" literal is stored in string pool.
    Line 2: "abcdef" literal gets stored in the string pool.
    Line 3: A new "xyz" literal is stored in the string pool and "str1" starts to point to this literal.
    Line 4: Since the value is generated by appending to another variable the result is stored in the heap memory and the literal being appended "ghi" will be checked for its existence in the string pool and will be created since it doesn't exist in the above case.

提交回复
热议问题