The Use of "new String(...)" in Java
When encountering the code structure "new String(...)" in Java, it's important to understand its purpose and effects. Unlike straightforward string assignments (e.g., "s = "Hello World";"), this syntax utilizes the "new" operator to create a String object by initializing it with a string constant.
Purpose of "new String(...)"
Although string constants reside in the constant pool, the behavior of "new String(...)" is not as straightforward as one might assume. While it creates a new String object, it does not necessarily result in the allocation of new memory on the heap.
Caveat of Forced Copy
One common misconception is that "new String(...)" forces a distinct copy of the internal character array. However, this behavior is implementation-dependent and undocumented. Attempting to achieve this by, for instance, "small=new String(huge.substring(10,20))" can lead to unexpected results, as the entire original character array may be retained, consuming significant memory.
Solution for Distinct Copies
To ensure a truly distinct copy of a character array, it's necessary to use "new String(huge.substring(10,20).toCharArray())." While this requires twice the memory copying (once for "toCharArray()" and once for the String constructor), it is the implementation-agnostic way to achieve the desired result.
Pitfalls of Assuming Documentation
It's crucial to note that documentation can sometimes lack clarity or accuracy. The documentation for "new String(...)" suggests it creates a copy of the "string," implying a copy of the supporting character array as well. However, as seen with the Apache Harmony implementation, this is not always the case.
Conclusion
Understanding the nuances of "new String(...)" in Java is essential to avoid potential pitfalls. While it may not always result in the intended behavior, it serves a specific purpose in some scenarios. However, it's recommended to proceed with caution and be aware of the implementation-dependent nature of this syntax.
The above is the detailed content of When and Why Should You Use `new String(...)` in Java?. For more information, please follow other related articles on the PHP Chinese website!