What is the purpose of the expression “new String(…)” in Java?

后端 未结 9 1026
迷失自我
迷失自我 2020-11-22 02:39

While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.

For example

9条回答
  •  有刺的猬
    2020-11-22 03:10

    String s1="foo"; literal will go in StringPool and s1 will refer.

    String s2="foo"; this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal.

    String s3=new String("foo"); "foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.

    String s4=new String("foo"); same as s3

    so System.out.println(s1==s2); //true due to literal comparison.

    and System.out.println(s3==s4);// false due to object comparison(s3 and s4 is created at different places in heap)

提交回复
热议问题