Java String Interning: Memory Efficiency and Pooling

𝐖𝐡𝐲 𝐉𝐚𝐯𝐚 𝐝𝐨𝐞𝐬𝐧'𝐭 "𝐝𝐨𝐮𝐛𝐥𝐞-𝐬𝐩𝐞𝐧𝐝" 𝐲𝐨𝐮𝐫 𝐦𝐞𝐦𝐨𝐫𝐲 🧠 In my last post, we talked about String Immutability. Today, let’s look under the hood at the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 (SCP). When you create a String in Java, the JVM is very stingy with your RAM. It has two ways to handle things: 1. 𝐓𝐡𝐞 "𝐍𝐞𝐰" 𝐖𝐚𝐲 (𝐄𝐱𝐩𝐥𝐢𝐜𝐢𝐭 𝐎𝐛𝐣𝐞𝐜𝐭 𝐂𝐫𝐞𝐚𝐭𝐢𝐨𝐧) 👉 String name = new String("Arpit"); This creates a brand new object in the Heap Memory, even if "Arpit" already exists elsewhere. It’s like buying a new book when there’s already a copy on the shelf. 2. 𝐓𝐡𝐞 𝐋𝐢𝐭𝐞𝐫𝐚𝐥 𝐖𝐚𝐲 (𝐓𝐡𝐞 𝐒𝐦𝐚𝐫𝐭 𝐖𝐚𝐲) 👉 String platform = "LinkedIn"; This tells the JVM: "Check the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 first." If "LinkedIn" is already there, your variable just points to it. If it’s not, it creates it. Result: 100 variables can point to the same "LinkedIn" string, saving massive amounts of memory. 𝐓𝐡𝐞 "𝐈𝐧𝐭𝐞𝐫𝐧" 𝐏𝐫𝐨-𝐓𝐢𝐩 💡 What if you created a string with new but want to move it into the pool to save space? Enter the .intern() method. As you can see in the 𝐝𝐢𝐚𝐠𝐫𝐚𝐦 (Credit: Scaler): - str1 and str3 point to the same "Java" in the pool. - str4 sits alone in the Heap. - str6 uses .intern() to jump from the Heap into the Pool! 𝐖𝐚𝐢𝐭, 𝐰𝐡𝐚𝐭 𝐚𝐛𝐨𝐮𝐭 𝐜𝐨𝐧𝐜𝐚𝐭𝐞𝐧𝐚𝐭𝐢𝐨𝐧? When you add two strings, Java creates a new string in the pool rather than changing the old one. This keeps your data safe and predictable. Did you know about this before? Let me know in the comments! 👇💭 #java #SoftwareEngineering #jvm #LearningInPublic

  • diagram

diagram is wrong inside SCP area no duplicate their (java / java )

To view or add a comment, sign in

Explore content categories