Sobes.tech
Junior

Why do we not create a string using the new String() constructor?

sobes.tech AI

Answer from AI

Creating a string with new String() always creates a new String object on the heap, even if a string with the same value already exists in the String Pool.

In contrast, string literals (e.g., "hello") are stored in the String Pool. If a string with the same value already exists in the String Pool, the existing object is used. Using literals allows the JVM to optimize memory usage.

Thus, new String() leads to unnecessary memory consumption and can reduce performance due to the creation of unnecessary objects. We prefer to use string literals or other string creation methods (like String.valueOf()) to save resources.

// Not recommended. Always creates a new object on the heap.
String str1 = new String("hello");

// Recommended. Uses String Pool, may reuse existing object.
String str2 = "hello";

// The comparison result can be different
System.out.println(str1 == str2); // Usually false, as they are different objects