Sub topic 2
Why Strings Are Immutable
A String is Java’s type for text. A string is immutable: once it is created, its text cannot change.
This does not mean a variable must always hold the same string. A variable is a named place for a value. You can make a string variable refer to different text later. But doing so does not change the original string.
Variables and shared strings
A string is an object, a value held in memory. A string variable holds a reference, which points to a string object. Two variables can hold references to the same string.
That is safe because neither variable can change the string’s text. If one variable is given a different reference, the other variable still refers to the original string.
Try it
Save this program as StringImmutability.java:
class StringImmutability {
public static void main(String[] args) {
String original = "cat";
String shared = original;
original.replace("c", "b");
System.out.println(original); // cat
String changed = original.replace("c", "b");
System.out.println(changed); // bat
System.out.println(shared); // cat
original = changed;
System.out.println(original); // bat
System.out.println(shared); // cat
}
}Compile and run it with a Java development kit installed:
javac StringImmutability.java
java StringImmutabilityThe lines printed by the program match the comments beside the print statements.
Here is what happens:
originalrefers to the string"cat". Thensharedreceives the same reference, so both variables refer to that string.replaceis a method, an action you can call on a value. It returns a string with the requested replacements. The first call returns"bat", but the program does not save the result.- The next call saves its result in
changed. The original string is still"cat". original = changedmakesoriginalrefer to"bat". It does not change"cat", andsharedstill refers to"cat".
An assignment is a statement that gives a variable a value. In the last step, the assignment changes what original refers to, not the text inside a string.
Why this matters
Immutability makes shared text predictable. You can give another part of a program a reference to a string without worrying that it will change the string’s contents.
It also explains a common mistake: calling a method such as replace and expecting the original variable’s text to change. Instead, use the returned string. If you want the variable to refer to that result, assign the result back to it.
Creating different text can require another string, so repeatedly making changes may use extra memory. The important rule is that the old string remains unchanged.
Exercise
Exercise
After String first = "sun"; String second = first; first = first.replace("s", "r");, what text does each variable refer to?
Show answer
first refers to "run", and second still refers to "sun". The replacement did not change the original string.