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

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

    String str = new String("hello")
    

    It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.

    An object will be created in a heap memory area and str reference points to object created in heap memory location.

    if you want str reference to point object containing in String constant pool then one has to explicitly call str.intern();

    String str = "world";
    

    It will check whether String constant pool already contains String "hello"? If present then it will not add an entry in String constant pool. If not present then it will add an entry in String constant pool.

    In both the above case, str reference points to String "world" present in Constant pool.

提交回复
热议问题