27

What is the difference between String str = new String("SOME") and String str="SOME" Does these declarations gives performance variation.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
JavaUser
  • 25,542
  • 46
  • 113
  • 139
  • See also http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly and http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java – polygenelubricants Sep 06 '10 at 17:41

4 Answers4

49
String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
10

There is a small difference between both.

Second declaration assignates the reference associated to the constant SOMEto the variable str

First declaration creates a new String having for value the value of the constant SOME and assignates its reference to the variable str.

In the first case, a second String has been created having the same value that SOME which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare transformed into the same instance, which uses far less memory.

As a consequence, always prefer second syntax.

Riduidel
  • 22,052
  • 14
  • 85
  • 185
  • 4
    For the record, there are scenarios where `new String(String)` makes sense, like if you have a very large string and you're only interested in retaining a small substring. The `substring` methods only return a flyweight view of the original string, so using `new String(hugeString.substring(a, b))` forces a copy and lets the GC reclaim the contents of `hugeString` when it goes out of scope. They shouldn't have made it a constructor, though... – gustafc Sep 06 '10 at 15:16
  • 1
    Interesting case of optimization, indeed, but I wouldn't go this path before having done some profiler checks (so would you, I guess). – Riduidel Sep 06 '10 at 15:41
1
String s1 = "Welcome"; // Does not create a new instance  
String s2 = new String("Welcome"); // Creates two objects and one reference variable  
terencey
  • 3,282
  • 4
  • 32
  • 40
0

First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.

Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.