2

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;
}
1
  • 5
    Where did you see this code? Commented Sep 30, 2015 at 8:04

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your help
0
"".value 

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.