Home >Java >javaTutorial >Java String Pool: Heap or Stack—Where Does a String Object Reside?
Java String Pool: Stack Allocation vs. Heap Storage
Consider the code snippet:
String first = "abc"; String second = new String("abc");
Instantiating a new String object with the new keyword creates a distinct String object on the heap. Unlike other primitives, String objects are immutable, meaning they cannot be modified after initialization.
However, Java maintains a String pool in the heap, which stores a limited number of commonly used Strings. When a literal String (enclosed in double quotes) is defined, the compiler checks the String pool for an existing matching String. If found, the literal String will reference the existing String in the pool, ensuring memory efficiency.
In this example, since "abc" is a literal String, it will be placed in the String pool.
Now, let's consider the new String object created with new String("abc"):
Therefore, our code results in one String in the String pool ("abc"") and one distinct String on the heap (the one created with new String("abc")).
The above is the detailed content of Java String Pool: Heap or Stack—Where Does a String Object Reside?. For more information, please follow other related articles on the PHP Chinese website!