Java String Immutability: Why Concat Doesn't Modify Original String

💡 Java Interview Question - String Immutability What will be the output? String s = "hello"; s.concat(" world"); System.out.println(s); Output: hello Why? Strings in Java are immutable. The concat() method creates a new String object instead of modifying the existing one. In this case, the result of concat() is not assigned back, so the original value remains unchanged. Correct approach: s = s.concat(" world"); Takeaway: If you don’t assign the result of a String operation, the change is lost. #Java #InterviewPrep #Programming

To view or add a comment, sign in

Explore content categories