In Java, "String literals" like "abc" are interned, meaning multiple references to the same literal value point to the same instance in memory. This helps optimize memory usage and performance. However, using new with a String literal, such as new String("abc"), creates a new String object, even if the literal already exists in the String pool.
Two statements regarding the String pool have raised some confusion:
To clarify, Statement 2 implies that String literals are still interned in the String pool even when creating an object with new, but a new object is constructed regardless.
In the example:
String one = new String("test"); String two = "test";
The reference passed to new String("test") is the same as two due to interning. However, a new String object with the value "test" is created and assigned to one.
Thus, there are two separate String objects with the value "test": one in the constant pool (referenced by two) and a new one created with new (referenced by one). That's why one.equals(two) is true (they have the same value), but one == two is false (they refer to different objects).
Statement 1 should be rephrased as "When the compiler encounters a String literal, it checks to see if an identical String already exists _in the pool_." Strings are only interned if they're explicitly interned or used as literals in class definitions.
The above is the detailed content of How Does the Java String Pool Handle `new String('literal')`?. For more information, please follow other related articles on the PHP Chinese website!