Home >Java >javaTutorial >Java String Pool: Heap or Stack—Where Does a String Object Reside?

Java String Pool: Heap or Stack—Where Does a String Object Reside?

DDD
DDDOriginal
2024-12-17 21:14:12892browse

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"):

  • A new String object is created on the heap, not in the String pool.
  • Despite being a copy of the literal "abc", this object will not be stored in the String pool.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn