Java String Comparison, Concatenation, and Immutability

💡 Part 2 — String Comparison, Concatenation & Immutability in Java In the previous post, we discussed how Strings, SCP, and intern() work in Java. Now let’s explore how they behave when we compare or modify them 👇 🔹 1️⃣ == vs .equals() String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ System.out.println(s1.equals(s2)); // true ✅ 👉 == → compares references (memory addresses) 👉 .equals() → compares values (content) If both strings come from the String Constant Pool (SCP), == can return true. But when we create new objects using new, they live in heap, so: String s1 = new String("Java"); String s2 = "Java"; System.out.println(s1 == s2); // false ❌ (different memory) 🔹 2️⃣ Compile-time vs Runtime Concatenation String s1 = "Ja" + "va"; String s2 = "Java"; System.out.println(s1 == s2); // true ✅ 👉 Concatenation of string literals happens at compile-time, so both refer to the same object in SCP. But when concatenation happens at runtime, a new object is created: String part = "Ja"; String s3 = part + "va"; System.out.println(s2 == s3); // false ❌ 🔹 3️⃣ Immutability of Strings String s = "abc"; s.concat("xyz"); System.out.println(s); // abc ❌ (unchanged) Strings are immutable — every modification creates a new object. To reflect the change, you must reassign: s = s.concat("xyz"); System.out.println(s); // abcxyz ✅ 🔹 4️⃣ Using intern() for Optimization If you want to make sure your heap string refers to SCP: String s1 = new String("Java"); String s2 = s1.intern(); System.out.println("Java" == s2); // true ✅ 👉 intern() makes your string memory-efficient and reusable. 🧠 Quick Recap ✅ == → reference check ✅ .equals() → content check ✅ Compile-time concat → stored in SCP ✅ Runtime concat → new object in heap ✅ Strings are immutable ✅ Use intern() for SCP optimization #Java #String #Coding #JavaDeveloper

To view or add a comment, sign in

Explore content categories