Reputation: 6036
I have investigated equals() method in String class and found that it uses value - an array of chars. Here this variable is:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
...
}
As a string is created then this value is immediately defined and seen in a debug mode. However I do not find a place where this value is defined.
My question. When we are creating a string like this:
String str = "My string";
how and when this value is defined?
Edit: I have seen 3 constructors that @xenteros mentioned. However this.value is defined as an array of chars only in the last constructor. Directly I am not invoking it. Also if you set breakpoints in these constructors it will not stop there.
Upvotes: 0
Views: 64
Reputation: 15852
value
is initialized in each constructor.
public String() {
this.value = new char[0];
}
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
When you execute
String str = "My string";
there is no magic happening. JVM
creates new String
calling a constructor. It's explained in the language specification
Edit:
In the JVM available in OpenJDK the following file contains the native code in which String literals are created. It's done in C++, so no Java constructors are called.
Upvotes: 2