Java String类中""的value取值及equals方法length赋值逻辑疑问
Let's walk through your questions using the code you shared from String.class:
1. How does the value field of "" get assigned in the empty String constructor?
Looking at the no-arg constructor:
public String() { this.value = "".value; }
Here's what's happening:
""is a compile-time constant empty String instance that the JVM creates and stores in the string constant pool. This single instance is reused across your entire application.- The
valuefield of this constant empty String is achar[]with a length of 0 (since there are no characters in an empty string). - The no-arg constructor doesn't create a new
char[]for the new String object. Instead, it directly references thevaluearray from the constant pool's empty String. This is a memory optimization—since Strings are immutable, sharing the empty array is safe and avoids unnecessary object duplication.
As the constructor's comment notes, using new String() is unnecessary because you can just use "" directly (it's the same underlying value, but avoids creating an extra String wrapper object).
2. Default behavior of String.equals() and the logic behind n = value.length
The equals() method is designed to check if two Strings represent the same sequence of characters, and it's optimized for performance:
Let's break down the step-by-step logic:
- Fast reference check: First, it checks if
this == anObject—if the two references point to the exact same object, it returnstrueimmediately. This is the cheapest check possible. - Type check: If the objects aren't the same, it verifies that
anObjectis a String instance. If not, returnsfalse(since non-String objects can't be equal to a String). - Length comparison:
n = value.lengthassigns the length of the current String's internal character array ton. Sincevalueis thechar[]that stores the String's characters,value.lengthis exactly the number of characters in the String.- It compares
ntoanotherString.value.length—if the lengths differ, the Strings can't be equal, so it returnsfalseright away. This is a critical optimization: comparing lengths first avoids the cost of iterating through all characters when the Strings are obviously different.
- Character-by-character comparison: If lengths match, it iterates through both
char[]arrays, comparing each character. If any pair of characters differs, it returnsfalse; if all match, returnstrue.
Why use value.length instead of the length() method?
The String.length() method actually just returns value.length under the hood:
public int length() { return value.length; }
Using value.length directly in equals() skips the method call overhead, which is a small but meaningful optimization for a frequently used method like equals().
内容的提问来源于stack exchange,提问作者user3627335

