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

前端 未结 23 2805

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:44

    I believe the main benefit of using the literal form (ie, "foo" rather than new String("foo")) is that all String literals are 'interned' by the VM. In other words it is added to a pool such that any other code that creates the same string will use the pooled String rather than creating a new instance.

    To illustrate, the following code will print true for the first line, but false for the second:

    System.out.println("foo" == "foo");
    System.out.println(new String("bar") == new String("bar"));
    

提交回复
热议问题