Home >Java >javaTutorial >String Constant Pool: Why Does \'new\' Create a New String Object Even When the Literal Exists?
String Constant Pool: An In-Depth Examination
String literals in Java are pooled to optimize memory usage and enhance performance. This means that when a String literal is encountered, the compiler checks the String Constant Pool for an existing String object with the same value. If found, the reference is directed to the existing object, avoiding the creation of a new one.
However, confusion arises when using the "new" operator to create a new String object, as this seemingly contradicts the rule of interning. To clarify this, let's examine the following statements:
These statements indicate that while the String literal is interned and stored in the pool, the use of "new" forces the JVM to create a new String object. This means that despite the existence of an equivalent String in the pool, the "new" operator bypasses it and allocates a new object in nonpool memory.
To illustrate this, consider the following example:
String one = new String("test"); String two = "test"; System.out.println(one.equals(two)); // true System.out.println(one == two); // false
As expected, the value of both "one" and "two" is "test," but the "==" comparison returns false because they refer to different String objects. This is because the use of "new" forces the creation of a new String object for "one," even though the String literal "test" already exists in the pool.
In summary, the String Constant Pool optimizes memory usage by interning String literals. However, the use of "new" bypasses the pool and creates a new String object in nonpool memory. This results in two distinct String objects with the same value but different references.
The above is the detailed content of String Constant Pool: Why Does \'new\' Create a New String Object Even When the Literal Exists?. For more information, please follow other related articles on the PHP Chinese website!