Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java string have a copy constructor? [duplicate]

Tags:

java

string

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) ?

like image 784
ripper234 Avatar asked Jul 12 '26 00:07

ripper234


1 Answers

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'.
like image 56
Adamski Avatar answered Jul 13 '26 13:07

Adamski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!