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

后端 未结 12 1115
悲&欢浪女
悲&欢浪女 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:00

    String literals will go into String Constant Pool.

    The below snapshot might help you to understand it visually to remember it for longer time.

    enter image description here


    Object creation line by line:

    String str1 = new String("java5");
    

    Using string literal "java5" in the constructor, a new string value is stored in string constant pool. Using new operator, a new string object is created in the heap with "java5" as value.

    String str2 = "java5"
    

    Reference "str2" is pointed to already stored value in string constant pool

    String str3 = new String(str2);
    

    A new string object is created in the heap with the same value as reference by "str2"

    String str4 = "java5";
    

    Reference "str4" is pointed to already stored value in string constant pool

    Total objects : Heap - 2, Pool - 1

    Further reading on Oracle community

提交回复
热议问题