How Many Objects Does a Java String Creation Actually Allocate?
This article explains how Java handles string literals and the new String() constructor, detailing when objects are created in the string constant pool versus the heap, and demonstrates the resulting reference comparisons with code examples.
1. String a = "abc" creates zero or one object. First a reference variable a is defined on the stack; the JVM checks the string constant pool for "abc". If it exists, a points to that pooled string; otherwise the literal is added to the pool and a points to it.
// When "abc" is not in the pool
// (1) three char values 'a','b','c' are created on the stack
// (2) a new String object is created on the heap from those chars
// (3) the String object is placed into the constant pool
// (4) a references the pooled object String a = "abc";
// equivalent to
char data[] = {'a','b','c'};
String a = new String(data);2. String a = new String("abc") creates one or two objects. A reference variable a is defined on the stack, then a new String object is allocated on the heap; a points to this object, which in turn references the pooled literal "abc".
3. Comparison
String a = "abc";
String b = "abc";
String c = new String("abc");
String d = new String("abc");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(c == d);Result: true, false, false. The expression new String("abc") always creates a new heap object regardless of the constant pool, so c and d refer to distinct objects, while a and b refer to the same pooled instance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Must-Have
Professional architects sharing high‑quality architecture insights. Covers high‑availability, high‑performance, high‑stability designs, big data, machine learning, Java, system, distributed and AI architectures, plus internet‑driven architectural adjustments and large‑scale practice. Open to idea‑driven, sharing architects for exchange and learning.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
