How String Pool works in Java: A Simple Explanation

𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹 𝗪𝗼𝗿𝗸𝗶𝗻𝗴 𝗼𝗳 𝘁𝗵𝗲 𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗼𝗼𝗹 𝗶𝗻 𝗝𝗮𝘃𝗮. This is a very common Java interview question, and many people still get confused about how the String Pool really works. Here’s the simple and correct explanation 👇 --- 1. String Pool is inside the heap memory In modern Java versions (Java 7+), the String Pool is a special managed area inside the heap, not outside. When you write: String s1 = "Java"; Java stores "Java" in the String Pool (if not already stored). --- 2. String literals always go to the pool String s1 = "Hello"; String s2 = "Hello"; Here, both s1 and s2 point to the same object in the pool. This saves memory and avoids duplicates. --- 3. new String("Java") creates a new heap object String s = new String("Java"); This always creates a new object in heap, even if "Java" already exists in the pool. But note: If the literal "Java" was not already in the pool, the JVM will first add the literal into the pool during class loading — not because of the new keyword. So final behavior: Literal "Java" → in pool New String object → in heap --- 4. intern() returns the pool version String s1 = new String("Java").intern(); String s2 = "Java"; Now both point to the same pool object. intern() simply returns the pooled instance. --- 5. Why String Pool exists? Because strings are used everywhere, and many repeat. The pool: Reduces memory usage Reuses common strings Improves performance --- 6. == vs equals() (Most asked in interviews) String a = "Hi"; String b = "Hi"; a == b; // true → same pool object But: String x = new String("Hi"); x == b; // false → heap object vs pool object == → checks reference (same object?) equals() → checks value (same text?) --- 💡 In short String Pool is inside heap String literals always go to the pool new String("Java") always creates a new heap object Literal is still stored in the pool by JVM (during class loading) intern() returns the pool version == compares references, equals() compares content This topic is simple but extremely important for both interviews and performance. #Java #StringPool #JavaInternals #InterviewPrep #BackendDevelopment #CodingConcepts #CleanCode #techieanky #javainterview #Stringpool #grow #linkedin

To view or add a comment, sign in

Explore content categories