Mastering Java Strings: A Clear Guide

💡 Mastering Java Strings - Once and For All 🚀 Strings in Java are simple to use… until you start comparing or modifying them. Let’s break it down clearly 👇 🔹 1️⃣ String Literals vs new String() String a = "abc"; // String literal → stored in String Pool String b = new String("abc"); // New object → stored in Heap 🔹 2️⃣ Reference Change String a = "abc"; a = "def"; System.out.println(a); ✅ Output: def Here, the reference of a changes from "abc" to "def". The original "abc" still exists in the String Pool, but a no longer points to it. Because Strings are immutable in Java, their values can’t be modified once created. 🔹 3️⃣ concat() Behavior String a = "abc"; a.concat("ghi"); System.out.println(a); ✅ Output: abc concat() creates a new String object "abcghi" but doesn’t change the original one. To update it, you must reassign: a = a.concat("ghi"); // Now a = "abcghi" 🔹 4️⃣ == vs .equals() String a = "abc"; String b = new String("abc"); System.out.println(a == b); // false → compares memory reference System.out.println(a.equals(b)); // true → compares actual content 🧠 If you do: String b = "abc"; Then both point to the same literal in the String Pool, so a == b → ✅ true. 🧩 Summary Concept Checks/Behavior Example Output Immutability - Value can’t change Reference change - Needs reassignment == - Compares reference false .equals() - Compares value true 💬 In short: Strings are immutable. == compares memory reference. .equals() compares actual content. Methods like concat() return a new object, not modify the old one. Once you get this, Strings in Java become super easy 💪 #Java #Programming #CodingTips #JavaDeveloper #Backend #Learning

To view or add a comment, sign in

Explore content categories