Java string intern and literal

后端 未结 5 552
太阳男子
太阳男子 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:24

    Yes, they are same. Basically intern() returns a representation of a string that is unique across the VM. This means you can use == instead of .equals() to compare the strings, saving on performance.

提交回复
热议问题