2

Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?

It's immutable, why would you need to invoke String.String(String str) ?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • Duplicate of http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly ? – VonC Nov 26 '09 at 12:04
  • 1
    Dupe: http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java, http://stackoverflow.com/questions/465627/use-of-the-stringstring-constructor-in-java – Pascal Thivent Nov 26 '09 at 12:04

3 Answers3

15

From the API doc:

Unless an explicit copy of original is needed, use of this constructor is
unnecessary since Strings are immutable. 

The only reason I can think of is in the situation where:

  1. You've created a very large String: A.
  2. You've created a small substring: B based on A. If you look at the implementation of substring you'll see it references the same char[] array as the original string.
  3. String A has gone out of scope and you wish to reduce memory consumption.
  4. Creating an explicit copy of B will mean that the copy: B' no longer references the large char[]. Allowing B to go out of scope will allow the garbage collector to reclaim the large char[] that backs A and B, leaving only the small char[] backing B'.
Adamski
  • 54,009
  • 15
  • 113
  • 152
3

new String(s) can help garbase collection:

String huge = ...;
String small = s.substring(0,2); //huge.value char[] is not garbage collected here
String gcFriendly = new String(small); //now huge.value char[] can be garbage collected
Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
  • 1
    How does that help garbage collection? One would end up with *more* garbage this way. – Paul Ruane Nov 26 '09 at 12:06
  • It helps garbage collection if you allow huge and small to go out of scope as gcFriendly does not reference the very large char[] that backs both huge and small. – Adamski Nov 26 '09 at 12:07
  • Accepted this and not the more detailed answer simply because of the code sample. – ripper234 Nov 27 '09 at 08:10
0

Just in case you need String that are not the same but equal.

Maybe for testing to make sure, people really do str.equals(str2) instead of (str == str2). But I never needed it.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268