String Pool
The String Pool is a special memory area where Java stores String literals (strings written directly with double quotes). If the same text is used again elsewhere in the program, Java reuses the existing object from the pool instead of crea…
1. What is the String Pool?
The String Pool is a special memory area where Java stores String literals (strings written directly with double quotes). If the same text is used again elsewhere in the program, Java reuses the existing object from the pool instead of creating a new one.
2. Why is it used?
This saves memory, since many programs repeat the same text values often. Instead of creating a new object every single time the same text appears, Java is smart enough to reuse what's already stored.
3. Real-Life Example
Think of a library with only one copy of a popular book. Instead of printing a fresh copy for every reader, the library lends out the same copy repeatedly. The String Pool works similarly — the same text value is "lent out" wherever it's needed instead of duplicated.
4. Syntax
javaString a = "Java"; // goes into the String Pool String b = "Java"; // reuses the same pooled object as 'a' String c = new String("Java"); // creates a separate object, NOT in the pool
5. Example Program
javapublic class StringPoolDemo { public static void main(String[] args) { String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); // true - same pooled object System.out.println(a == c); // false - different object in heap } }
Output:
true
false6. Key Points to Remember
Stringliterals go into the pool automatically;new String()always creates a separate object outside the pool.- Use
.equals()to compare string content, and reserve==only for checking if two references point to the exact same object. - This String Pool behaviour is a very frequently asked Java interview question.