Strings are Objects in Java: Why No 'new' for Creation?
Strings in Java are objects, yet unlike other objects, they are commonly created without using the 'new' keyword. This practice raises the question of why 'new' is not necessary for string creation.
Reason for Not Using 'new': String Interning
Rather than creating a new String object each time a string literal is used, Java performs a process known as interning. Interning involves storing string literals in a central pool, known as the string pool. When a string literal is encountered, it is checked against the string pool. If an identical string literal already exists, a reference to the existing string is returned, instead of creating a new object.
Example:
Consider the following code:
String str1 = "Hello"; String str2 = "Hello";
In this example, both 'str1' and 'str2' reference the same String object in the string pool, despite being created separately. As a result, 'str1 == str2' evaluates to true, indicating that they are physically equal.
Advantage of Interning:
Interning optimizes performance by reducing the number of String objects created, especially for frequently used strings. For instance, in a loop where a string literal is used multiple times, only one String object is created, rather than recreating it each iteration, leading to significant memory savings.
Creating Strings with 'new'
While interning is the recommended approach, it is still possible to create Strings using 'new'. However, it is important to note that this can result in multiple String objects being created for the same string value, which may impact memory usage and performance.
Conclusion:
The absence of 'new' in string creation in Java stems from the use of string interning. Interning improves performance by reducing unnecessary object creation and promoting memory efficiency, making it the preferred method for creating strings.
The above is the detailed content of Why Don't We Use 'new' to Create Strings in Java?. For more information, please follow other related articles on the PHP Chinese website!