When you try to change a String, Java creates a new String object instead of changing the original one.
code_blocksExecution Sample
Java
String s = "Hello";
s.concat(" World");
System.out.println(s);
s = s.concat(" World");
System.out.println(s);
This code shows that calling concat does not change the original String unless reassigned.
data_tableExecution Table
Step
Code executed
String s value
Action
Output
1
String s = "Hello";
"Hello"
Create s with "Hello"
2
s.concat(" World");
"Hello"
Create new String "Hello World" but do not assign
3
System.out.println(s);
"Hello"
Print s
Hello
4
s = s.concat(" World");
"Hello World"
Assign new String to s
5
System.out.println(s);
"Hello World"
Print s
Hello World
💡 Program ends after printing both values of s showing immutability effect
search_insightsVariable Tracker
Variable
Start
After Step 2
After Step 4
Final
s
"Hello"
"Hello"
"Hello World"
"Hello World"
keyKey Moments - 2 Insights
▶Why does s.concat(" World") not change s immediately?
▶What happens if you print s right after s.concat(" World") without assignment?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of s after step 2?
A"Hello"
B"Hello World"
Cnull
DCompilation error
photo_cameraConcept Snapshot
String immutability in Java means once a String is created, it cannot be changed.
Methods like concat() create new Strings instead of modifying the original.
To update a String variable, assign the new String back to it.
Example:
String s = "Hi";
s = s.concat(" there"); // s now "Hi there"
contractFull Transcript
This visual trace shows how Java Strings are immutable. When we create a String s with "Hello", it holds that value. Calling s.concat(" World") creates a new String "Hello World" but does not change s itself. Only when we assign the result back to s does s point to the new String. Printing s before assignment shows the original value. This teaches that String methods that seem to change the String actually return new Strings, preserving immutability.