Reputation: 1601
Say I have a method:
public String getString() {
char[] array = new char[]{'a', 'b', 'c'};
return new String(array);
}
Is the array still copied in the String constructor or is the Java compiler smart enough to recognize that the elements in the array cannot change so it can just reference the array?
Thanks
Upvotes: 2
Views: 251
Reputation:
See the source of java.lang.String
:
/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* @param value
* The initial value of the string
*/
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
Edit:
See also the source of java.util.Arrays
which calls System.arraycopy
.
Upvotes: 4
Reputation: 37516
Look at this contructor too:
153 public String(String original) {
154 this.value = original`.value;
155 this.hash = original.hash;
156 }
This would be a string literal:
"abc"
Which is just a call to String(char[] value)
with a, b, c passed in as elements of a char array. In short, String x = "abc"
is just syntactic sugar that compiler provides you to get around what you are doing above.
Upvotes: 1
Reputation: 425238
The answer should be obvious: For String
to remain immutable, it must defensively copy the array.
Consider this code:
public String getString() {
char[] array = new char[]{'a', 'b', 'c'};
String s = new String(array); // abc
array[0] = 'x';
return s; // xbc
}
If the array is not copied, the backing array will have leaked out, exposing the String to mutability.
Upvotes: 1
Reputation: 51453
Since the java String
class is immutable the constructor must copy the array.
Otherwise someone can hold a reference to the array and modify it:
char[] array = new char[]{'a', 'b', 'c'};
String string = new String(array);
array[1] = 'd'; // array modification must NOT affect the string
Upvotes: 6
Reputation: 68715
If you see the source code, you will get your answer. The input array is copied and not referenced. Here is the source code:
public String(char value[]) {
this.offset = 0;
this.count = value.length;
this.value = StringValue.from(value);
}
static char[] from(char[] value) {
return Arrays.copyOf(value, value.length);
}
Upvotes: 0