Sub topic 2
Why Strings Are Immutable
A Java String is an object that holds text. An object is a value with methods that can perform operations. A method is an action you call on an object, such as asking a string to replace some text.
Strings are immutable. This means that once a String object is created, the text inside it cannot be changed. You can still make a different string from it, or make a variable point to a different string.
This matters because you can pass a string to another part of a program without worrying that its text will change. It also explains a common beginner mistake: calling a method that produces changed text, but forgetting to save the result.
A variable can change, even when a string cannot
A variable is a named place for storing a value. A String variable holds a reference, which is a way to refer to a String object.
Consider this line:
String drink = "green tea";
The text "green tea" is a string literal: text written between double quotes in Java code. The variable drink refers to a String object holding that text.
You can later write:
drink = "black tea";
This is an assignment: it gives the variable a value. It makes drink refer to a different string. It does not change the text inside the original "green tea" string.
Think of a string as a printed label. You cannot edit the printed words, but you can point to a different label.
Methods give you results
Some string methods produce text based on an existing string. For example, replace looks for one piece of text and gives you a string with replacements.
In drink.replace("green", "black"), the pieces of text inside the parentheses are arguments: values given to the method. The method’s return value is the result it gives back.
If drink refers to "green tea", that call returns "black tea". The original string still holds "green tea".
You can save the result in another variable:
String changed = drink.replace("green", "black");
Or you can assign it back to the same variable:
drink = drink.replace("green", "black");
In the second line, Java first calls the method using the current value of drink. Then it assigns the result to drink. The original string is not edited.
An ignored result
This line is allowed, but it does not update drink:
drink.replace("green", "black");
The method returns a result, but the line does not save it. Afterward, drink still refers to the same text as before. If you need the changed text, use the return value.
Worked example: keeping and changing text
Create a file named ImmutableStrings.java and put this code in it:
public class ImmutableStrings {
public static void main(String[] args) {
String message = "green tea";
String saved = message;
String revised = message.replace("green", "black");
System.out.println("message: " + message);
System.out.println("saved: " + saved);
System.out.println("revised: " + revised);
message.replace("tea", "coffee");
System.out.println("after ignored result: " + message);
message = revised;
System.out.println("after assignment: " + message);
System.out.println("saved: " + saved);
message = message.replace("tea", "coffee");
System.out.println("after replacement: " + message);
System.out.println("revised: " + revised);
}
}Compile and run it from the folder containing the file:
javac ImmutableStrings.java
java ImmutableStringsYou should see:
message: green tea
saved: green tea
revised: black tea
after ignored result: green tea
after assignment: black tea
saved: green tea
after replacement: black coffee
revised: black teaFollow the references
At the start, message refers to "green tea". The assignment String saved = message; copies that reference, so saved refers to the same string.
Next, replace gives back "black tea", and revised refers to that result. Neither message nor saved has changed.
The next call tries to replace "tea" with "coffee", but its result is ignored. That is why message still shows "green tea".
After message = revised;, both message and revised refer to "black tea". The variable saved still refers to "green tea":
Finally, the program saves the result of replacing "tea" with "coffee" in message. Now message refers to "black coffee". The variable revised still refers to "black tea".
Reassigning one variable does not reassign another, even if they previously referred to the same string.
Why sharing a string is useful
Suppose a program saves a customer’s chosen name in one place and passes it to another part of the program. Both places can refer to the same string safely: neither can change the text inside it.
Either place can make a different string and use that instead. But doing so will not silently change the original text held by the other place. This makes the flow of text easier to follow and helps prevent mistakes.
Immutability does not mean a program’s text values can never change. It means that a change is represented by a different string value, rather than an edit to the existing string.
Does every call make a new object?
Do not rely on a method making a brand-new object every time. If a method has no change to make, it may return the existing string. For example, replacing "cat" with "dog" in "bird" leaves the text unchanged.
The important rule is about the text: a string method cannot change the contents of the original String. Use the returned value when you want to keep the result, and do not depend on whether Java made a separate object.
Strings and `final` are different ideas
You may see a variable declared with final. A final variable can be assigned only once. For a String variable, that means you cannot later make the variable refer to a different string.
A string is immutable whether or not its variable is final. Immutability protects the string’s text. final restricts assignment to the variable.
Check your understanding
When a string operation seems to have had no effect, ask:
- Did the method return a result that I need?
- Did I save or use that result?
- Am I looking at the variable I reassigned, rather than another variable that still refers to the old string?
Exercise
If name refers to "Mina", what does name contain after calling name.replace("M", "T") without saving the result?
Show answer
It still refers to "Mina". The returned "Tina" was not saved.
Exercise
If first and second both refer to "sun", what happens to second when first is reassigned to "moon"?
Show answer
second still refers to "sun". Reassigning first does not change second or the original string.