Understanding String, SCP, and intern() in Java

💡 Understanding String, String Constant Pool & intern() in Java String is one of the most commonly used and yet most misunderstood classes. Let’s break it down clearly 👇 🔹 1️⃣ String in Java String is a final and immutable class in java.lang package. Once a String object is created, it cannot be modified. Any change (like concatenation or case conversion) creates a new String object in memory. String s = "Hello"; s.concat("Java"); System.out.println(s); // Output: Hello (unchanged) Here, a new object "HelloJava" is created, but s still refers to "Hello". 🔹 2️⃣ String Constant Pool (SCP) SCP is a special area inside the heap memory used to store unique String literals. When you create a string literal like: String s1 = "Java"; String s2 = "Java"; 👉 Both s1 and s2 point to the same object in the SCP (no duplicate literal is created). This optimization saves memory and improves performance. 🔹 3️⃣ The intern() Method intern() ensures that your String uses the SCP reference. If a string with the same value already exists in the SCP, intern() returns that reference. Otherwise, it adds the string to SCP and then returns its reference. String s1 = new String("Java"); String s2 = s1.intern(); System.out.println(s1 == s2); // false ❌ (heap vs SCP) System.out.println("Java" == s2); // true ✅ (both in SCP) ✅ In short: String literals → go to SCP automatically new String() → stored in heap intern() → moves or points the string to SCP 🧠 Key Takeaways Strings are immutable and memory-efficient. SCP avoids duplicate string literals. intern() helps in reusing strings and saving heap space. #Java #String #JavaDeveloper #Coding #Programming

To view or add a comment, sign in

Explore content categories