Java Immutable Strings and Reassignment

💡 Java Interview Question – Immutable Strings Trap What will be the output? String s = "Java"; s.replace("J", "K"); System.out.println(s); 🤔 Options: A) Kava B) Java C) Compilation Error D) Runtime Exception --- ✅ Correct Answer: B) Java --- 🔍 Explanation: In Java, String is immutable. That means once a String object is created, it cannot be modified. 👉 The "replace()" method does not change the original string, it returns a new modified string. But here’s the catch 👇 s.replace("J", "K"); We are not assigning the result back to "s", so the original value remains unchanged. --- 💡 Correct way to modify: s = s.replace("J", "K"); System.out.println(s); // Output: Kava --- 🚀 Key Takeaway: Always remember: 👉 Strings in Java are immutable → Reassignment is required for changes --- #Java #JavaInterview #Coding #BackendDevelopment #Programming #InterviewPrep

To view or add a comment, sign in

Explore content categories