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.
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.
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.
Lobster Programming
Sharing insights on technical analysis and exchange, making life better through technology.
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.
