Java string intern and literal

后端 未结 5 551
太阳男子
太阳男子 2020-11-29 08:58

Are the below two pieces of code the same?

String foo = \"foo\";
String foo = new String(\"foo\").intern();
5条回答
  •  臣服心动
    2020-11-29 09:07

    The first one i.e.

        String foo = "foo";
    

    in this line, we are creating a String using String literals. That means the string is automatically saved in String Constant pool.

    In the 2nd one , i.e. -

        String foo = new String("foo").intern();
    

    Here we are creating a String using new String() & then manually saving it to the String constant pool. If we didn't have mentiones intern() , it would not have saved in the String constant pool.

    For more clarification, please refer to this link -

    http://javacodingtutorial.blogspot.com/2013/12/comparing-string-objects-intern-other.html

提交回复
热议问题