Java, Software Development

Java – Beyond String Pool

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.

These codes output the following.

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.

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.

Explicit Interning

The other name for the String Pool is the Intern Pool. Consider these codes.

To pick up the String "Martin" from the String Pool, we can update the codes to this:

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like