The String Pool
is a location in the Java Virtual Machine (JVM)
that collects all the literal Strings
from your codes. Java keeps unique Strings
for reuse.
Basic Idea
Let’s say we have these two (2) strings.
1 2 3 4 5 6 | String aname = "Martin"; String anotherName = "Martin"; // Are they referring to the same reference? System.out.println("Same reference? " + (aname == anotherName)); |
These codes output the following.
1 | Same reference? true |
So that is the basic idea that shows the effect of the String Pool
. This also applies to String
literals in different locations (e.g., class or package).
Other Rules
There are other situations where the String Pool
is at work.
Computed Strings by constant expressions
Strings can be computed (or derived) during compile-time or run-time.
Compile-time
For compile-time, strings are derived by or using constants expressions. For example, the following codes.
1 2 3 4 5 | String aname = "Martin"; String anameFromConstants = "Mar" + "tin"; System.out.println("Same reference? " + (aname == anameFromConstants)); |
As you can see, anameFromConstants
was derived from two string literals. The compiler combines these into a single string literal.
The codes output the following.
1 | Same reference? true |
Explicit Interning
The other name for the String Pool
is the Intern Pool
. Consider these codes.
1 2 3 4 5 6 | String aname = "Martin"; String anameDynamic = "I do know Martin from the Bronx".substring(10, 16); // Displays "Same reference? false" System.out.println("Same reference? " + (aname == anameDynamic)); |
To pick up the String "Martin"
from the String Pool
, we can update the codes to this:
1 2 3 4 5 6 7 | String aname = "Martin"; String anameDynamic = "I do know Martin from the Bronx".substring(10, 16); String sameAname = anameDynamic.intern(); System.out.println("Same reference? " + (aname == sameAname)); |