Introduction:
The String Constant Pool is a feature of the Java Virtual Machine (JVM) that stores constant values, including String literals. When the JVM encounters a String literal during compilation, it checks the pool for an existing one with the same value. If found, the reference to the new literal is directed to the existing String, avoiding the creation of a new instance.
Interning with "new" Keyword:
However, the use of the "new" keyword when creating a new String object introduces a different behavior, as outlined in the references provided. While the reference to the String literal ("test" in this case) will still be placed in the pool, the JVM is obligated to create a new String object at runtime instead of reusing the one from the pool.
Question:
If the reference to the String literal in the pool is the same as when created with "new," shouldn't the JVM return the existing reference instead of creating a new one?
Answer:
No, the JVM will not return the existing reference when the "new" operator is used. Instead, it will create a new String object and assign it to the reference created by the "new" keyword. This is because:
Example:
<code class="java">String literal = "test"; String one = new String(literal); String two = "test"; System.out.println(literal == two); // true (references in pool) System.out.println(one == two); // false (distinct objects)</code>
In this example, the "literal" and "two" references point to the same String object in the pool. However, the "one" reference points to a different String object created by "new." Therefore, the equality comparison using "==" returns false.
Clarification:
The statement "When the compiler encounters a String literal, it checks the pool to see if an identical String already exists" should be interpreted as "in the pool," meaning only String literals that have been interned or explicitly added to the pool will be considered for interning.
The above is the detailed content of Why Does Java Create a New String Object Even When a Reference to the Same Literal Exists in the Constant Pool?. For more information, please follow other related articles on the PHP Chinese website!