Home  >  Article  >  Java  >  How Does the Java String Pool Handle `new String(\"literal\")`?

How Does the Java String Pool Handle `new String(\"literal\")`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 12:11:29840browse

How Does the Java String Pool Handle `new String(

String Constant Pool: Clarifying Misconceptions

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:

  • Statement 1: "When the compiler encounters a String literal, it checks the pool to see if an identical String already exists."
  • Statement 2: "When you use new with a String literal, references to the literal are still put into the constant table (the String Literal Pool), but the JVM creates a new String object at run-time."

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn