javastringperformanceobjectinstantiation

Best approach of Creating String Object


In java we can create String in the following 2 ways -

String str1 = new String("first string");  //1

String str2 = "second string";  //2

Is there any difference in performance with these 2 approaches? And in the second case is there any new String object created?
Thanks in advance.


Solution

  • The first approach forces the creation of a new String object. The second allows java to use the constant from the string pool, and should generally be preferred.