How Many Objects Does `String a = "abc"` Actually Create in Java?
This article explains how Java handles string literals and `new String()` expressions, detailing when objects are created in the string constant pool versus the heap, and demonstrates the resulting reference comparisons with example code.
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 instance; otherwise the literal is added to the pool and a points to it.
// When "abc" is not in the constant pool
// 1) three char values 'a','b','c' are created on the stack
// 2) a new String object is created on the heap using those chars
// 3) that 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 and a points to it; the newly created object also references the literal in the constant pool.
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);Output: true, false, false. The `new String("abc")` expression 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.
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.
