Sobes.tech
Junior

What is the difference between creating a string with new String() and using a string literal?

sobes.tech AI

Answer from AI

When using a string literal ("abc"), the string is created in the String Pool. If a string with the same value already exists in the pool, a reference to the existing object is returned. This is an optimization for memory saving.

When using new String("abc"), a new string object is always created on the heap, even if a string with the same value already exists in the String Pool.

Example:

// A string literal "hello" is created. If such a string does not exist in the pool, it is added.
// str1 references the object in the pool.
String str1 = "hello";

// The literal "hello" is used again. Since it already exists in the pool,
// str2 also references the same object in the pool as str1.
String str2 = "hello";

// A new string object with the value "hello" is created on the heap.
// str3 references this new object on the heap, not the object in the pool.
String str3 = new String("hello");

// Reference checks:
// str1 and str2 refer to the same object in the pool.
System.out.println(str1 == str2); // true

// str1 refers to the object in the pool, str3 to a new object on the heap.
System.out.println(str1 == str3); // false

// Value check:
// All strings have the same value.
System.out.println(str1.equals(str3)); // true

Differences in the table:

Criterion String literal ("abc") new String("abc")
Creation location String Pool Heap
Object creation Returns existing or creates new Always creates a new object
Memory optimization Efficiently uses the pool for repetitions May create duplicates, less efficient
Reference comparison (==) Often true for strings with the same value Always false for separately created strings
What is the difference between creating a string with… - sobes.tech