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"