What is string pool in Java
In Java, the String pool (or String literal pool) is a special area in the JVM (Java Virtual Machine) where String objects are stored. When you create a String object using a string literal (i.e., within double quotes), the JVM checks the String pool first. If the string already exists in the pool, a reference to the existing String object is returned. If not, a new String object is created in the pool, and its reference is returned.
String pooling is done to conserve memory by reusing String objects whenever possible, which is especially useful since strings are immutable in Java (i.e., their values cannot be changed once they are created).
Here’s an example to illustrate how the String pool works:
In this example:
str2both refer to the same String object in the String pool because they are created using string literals.
str3is created using the
newkeyword, so it creates a new String object in the heap memory.
- By calling
str3, it is interned, meaning a reference to the String object in the pool is returned. After interning,
str3both refer to the same String object in the pool.
String pooling is particularly useful when you’re dealing with a large number of strings, as it helps conserve memory by reusing common strings instead of creating new objects for every occurrence of the same string value.