"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > String Constant Pool: Why Does \"new\" Create a New String Object Even When the Literal Exists?

String Constant Pool: Why Does \"new\" Create a New String Object Even When the Literal Exists?

Published on 2024-11-06
Browse:917

String Constant Pool: Why Does \

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:

  • "When the compiler encounters a String literal, it checks the pool to see if an identical String already exists."
  • "In the case of 'new,' references to String literals are still put into the constant table, but when you use 'new,' the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table."

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3