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

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

    When you store a String as

    String string1 = "Hello";
    

    directly, then JVM creates a String object with the given price during a separate block of memory called String constant pool.

    And whenever we have a tendency to try and produce another String as

    String string2 = "Hello";
    

    JVM verifies whether or not any String object with constant price exists within the String constant pool, if so, rather than making a brand new object JVM assigns the reference of the existing object to the new variable.

    And when we store String as

    String string = new String("Hello");
    

    using the new keyword, a brand new object with the given price is made no matter the contents of the String constant pool.

提交回复
热议问题