Difficulty: Medium
Correct Answer: A string literal may reuse an existing String object from the string pool, while new String() always creates a new String object on the heap even for the same text.
Explanation:
Introduction / Context:
String handling is a very common topic in Java interviews. Understanding the difference between using string literals and constructing strings with the new keyword helps developers reason about memory usage, object identity, and performance. This question focuses on how the JVM manages string instances through the string pool.
Given Data / Assumptions:
Concept / Approach:
The JVM maintains a special area called the string pool that stores unique instances of string literals and interned strings. When code uses the same literal in multiple places, the compiler and JVM can reuse the same pooled object. In contrast, using new String(\"text\") explicitly requests a new String object, even if an identical value already exists in the pool. As a result, comparing string references with == can behave differently for literals and for objects created with new.
Step-by-Step Solution:
Verification / Alternative check:
A small test program that prints the result of == comparisons between literals and new String() instances clearly shows the effect. Tools such as debuggers or heap analyzers also reveal separate objects when new String() is used repeatedly for the same value.
Why Other Options Are Wrong:
Common Pitfalls:
A common mistake is to use new String() without need, which creates unnecessary objects and can hurt performance. Another pitfall is comparing strings with == instead of equals(), which leads to subtle bugs when pooled and non pooled instances are mixed.
Final Answer:
The correct choice is A string literal may reuse an existing String object from the string pool, while new String() always creates a new String object on the heap even for the same text. because this captures the key memory and identity differences between literals and explicit construction.
Discussion & Comments