Sobes.tech
Junior

What is the difference between creating a string with double quotes and calling the new String constructor?

sobes.tech AI

Answer from AI

When creating a string using double quotes ("string"), the JVM searches the String Pool for a string with the same content. If such a string is found, a reference to the existing object is returned. If not, a new string object is created in the String Pool, and a reference to it is returned. This optimizes memory usage, as identical string literals refer to the same object.

When creating a string using the constructor new String("string"), a new string object is always created outside the String Pool, even if a string with the same content already exists in the pool.

Differences:

  • String Pool: Double quotes use the String Pool, new String does not.
  • Performance: Using double quotes is usually faster because existing objects can be reused.
  • Number of objects: Double quotes can lead to fewer string objects in memory compared to multiple uses of new String with the same content.
  • Comparison:
    • When comparing strings created with double quotes with the same content, the == operator returns true because they refer to the same object.
    • When comparing strings created with new String (even with the same content) or a string created with double quotes to a string created with new String, the == operator returns false because they are different objects. To compare string contents, always use the equals() method.

Example:

// Created in the String Pool (or reused)
String s1 = "abc";

// Created in the String Pool (reuses the "abc" object from the pool)
String s2 = "abc";

// Creates a new object outside the String Pool
String s3 = new String("abc");

// Creates a new object outside the String Pool
String s4 = new String("abc");

// s1 == s2 -> true (refers to the same object in the pool)
// s1 == s3 -> false (different objects)
// s3 == s4 -> false (different objects)

// s1.equals(s2) -> true (same content)
// s1.equals(s3) -> true (same content)
// s3.equals(s4) -> true (same content)