Java String Pool

In Java, String literal allocation to variables like:

String oneLiteral = "imaliteral"

is not leading to a new String Object creation in the Heap but rather is using a String Pool following the Flyweight Design Pattern. Following the pattern there is a repository of already used literals that are getting reused/re-allocated to String variables upon request.

Looking at the bytecode footprint of:

String oneLiteral = "imaliteral";
String anotherLiteral = "imaliteral"

we descover that the ldc opcode is used for the same string litteral to be placed in the stack. Therefore at compile time all the same literals are “bytecode-ed” to reference the same String in the String pool. This makes it possible to compare using

During runtime, access to the String pool is only through explicit call of the String#intern() method making sure the following evaluates to true:

("fly"+"weight").intern() == "flyweight"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s