Clarifying Java String Creation: Revisiting "String s = new String("silly")"
In Java, the creation of String objects is a topic that often raises questions. One such question pertains to the difference in usage between String and other classes when assigning literals.
Why is "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" Correct?
The statement "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" is indeed correct because String is a unique class in Java. This behavior is not applicable to other classes, such as CaseInsensitiveString.
Understanding String's Special Behavior:
Unlike other classes, String has certain inherent characteristics that allow this unique behavior:
How to Make CaseInsensitiveString Behave Like String:
To make CaseInsensitiveString behave like String in this regard, you would need to override its constructor and manually intern the passed-in String literal into the string pool. This would require access to the JVM's internal string pool and could result in performance issues if not done carefully.
Conclusion:
In summary, String is a unique class in Java that allows for simplified initialization with literals. Other classes, such as CaseInsensitiveString, do not have this behavior and require explicit construction using their proper constructors.
The above is the detailed content of Why Can't I Use `new CaseInsensitiveString('Polish')` Like I Do With `new String('silly')`?. For more information, please follow other related articles on the PHP Chinese website!