Java String Concatenation: Immutable Objects and Memory Allocation

🔥 Tricky Java String Concatenation Test public class StringConcate { public static void main(String[] args) { String s1 = "Welcome"; String s2 = new String("To"); String s3 = new String(); //Case 1 s1.concat("Java"); System.out.println(s1); //case 2 s3=s1.concat("Java"); System.out.println(s3); //case3 s3=s1+s2; System.out.println(s3); } } Guess the output ? 👏 Let understand We have created 🧠 Memory Creation 🔹 s1 → String Constant Pool (SCP) → "Welcome" 🔹 s2 → Heap memory (created using new) 🔹 s3 → Empty String object in Heap 📌 Important: 👉 All String objects in Java are immutable 🔹 Case 1 s1.concat("Java"); System.out.println(s1); concat() creates a new String → "WelcomeJava" Result is not assigned s1 still points to "Welcome" ✅ Output :Welcome 🔹 Case 2 s3 = s1.concat("Java"); System.out.println(s3); New String "WelcomeJava" is created This time, it is assigned to s3 s1 remains unchanged ✅ Output : WelcomeJava 🔹 Case 3 s3 = s1 + s2; System.out.println(s3); + operator is used Internally converted to: new StringBuilder() .append(s1) .append(s2) .toString(); A new String object is created Assigned to s3 ✅ Output : WelcomeTo #Java #String #JavaInterview #CoreJava #StringImmutability #Developer #CodingInterview

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories