Fundamentals 3 min read

How Many Objects Does Java Create for Different String Initializations?

This article explains how Java creates objects for various String assignments—using new String("long"), a literal "long", or concatenated literals "lo" + "ng"—detailing when one or two objects are allocated based on the presence of the literal in the string constant pool.

Lobster Programming
Lobster Programming
Lobster Programming
How Many Objects Does Java Create for Different String Initializations?

We analyze how many objects are created for String s = "long" , new String("long") , and String s = "lo" + "ng" using diagrams.

1. Objects created by String s = new String("long")

String s = new String("long") creates a String object and the variable s on the stack points to this instance, as shown:

The literal "long" is a string; the JVM first checks the string constant pool for this literal. If it does not exist, a constant object is created, as illustrated:

Finally, the string object references the "long" in the constant pool:

Therefore, if "long" is not already in the constant pool, String s = new String("long") creates two objects; otherwise, it creates only one.

2. Objects created by String s = "long"

The JVM checks the constant pool for the literal "long". If absent, it creates a constant object; if present, it reuses the existing one. Hence, String s = "long" may create an object or may not.

3. Objects created by String s = "lo" + "ng"

The compiler optimizes this concatenation, storing the resulting literal "long" in the constant pool. Consequently, String s = "lo" + "ng" behaves the same as String s = "long" regarding object creation.

javaMemory ManagementObject CreationstringConstant Pool
Lobster Programming
Written by

Lobster Programming

Sharing insights on technical analysis and exchange, making life better through technology.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.