Java Strings: “String s = new String(”silly“);”

前端 未结 23 2487

I\'m a C++ guy learning Java. I\'m reading Effective Java and something confused me. It says never to write code like this:

String s = new String(\"silly\");         


        
23条回答
  •  心在旅途
    2020-11-22 14:47

    String s1="foo";
    

    literal will go in pool 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)

提交回复
热议问题