Risk4U
Risk4U

Reputation: 33

Java String transform to char array

I want to ask how does the "".value transform char array,Thanks

public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];

/**
 * Initializes a newly created {@code String} object so that it represents
 * an empty character sequence.  Note that use of this constructor is
 * unnecessary since Strings are immutable.
 */
public String() {
    this.value = "".value;
}

Upvotes: 2

Views: 122

Answers (2)

Holger
Holger

Reputation: 298143

You should tell, which JRE implementation you are looking at, when you cite its source code.

However, the code is quite simple:

  • "" refers to a String constant which is initialized by the JVM
  • since you are inside the String() constructor which may get called by application code, but not JVM internal initialization, it may safely refer to the "" constant
  • like any other String object, it has the value field, so inside the String constructor, it is no problem to access that private field and copy the reference; it is equivalent to

    String tmp = "";
    this.value = tmp.value;
    

Since both, the "" constant and the instance created with the String() constructor represent empty strings, there is no problem in sharing the char[] array instance between them. However, there are reasons against it:

  • it is optimizing an uncommon case, as there is usually no reason to ever use the String() constructor at all
  • it is fragile as it relies on a particular JVM behavior, i.e. that the constant "" is not constructed via the String() constructor; if that assumption is wrong, this implementation will create a circular dependency

Upvotes: 4

Michal
Michal

Reputation: 2423

"".value 

creates empty char[] array, equivalent of this.value = new char[0];

Upvotes: 0

Related Questions