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

前端 未结 23 2796

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

     String str1 = "foo"; 
     String str2 = "foo"; 
    

    Both str1 and str2 belongs to tha same String object, "foo", b'coz Java manages Strings in StringPool, so if a new variable refers to the same String, it doesn't create another one rather assign the same alerady present in StringPool.

     String str1 = new String("foo"); 
     String str2 = new String("foo");
    

    Here both str1 and str2 belongs to different Objects, b'coz new String() forcefully create a new String Object.

提交回复
热议问题