Sub topic 1
Why Strings Are Immutable
A String is an object that represents a sequence of characters. In Java, a String is immutable, which means that its character content cannot change after the object is created.
This rule applies to every String object. A variable that refers to a string can point to a different string later, but the original string remains unchanged.
Prerequisites
This chapter assumes that you can declare variables, call methods, use the + operator, and run a basic Java program. You should also know that variables hold references to objects, while objects hold their own data.
An Immutable Object
Consider this code:
String word = "cat";
word = word.toUpperCase();
System.out.println(word);The output is:
CATIt may appear that toUpperCase() changed "cat". It did not. The method created another String containing "CAT", and the variable word was updated to refer to that new object.
The original string "cat" still exists unchanged if another reference points to it:
String original = "cat";
String upper = original.toUpperCase();
System.out.println(original); // cat
System.out.println(upper); // CATThe method call produces a result. It does not modify original.
This behavior applies to common string methods such as replace, trim, substring, and toLowerCase. When a method appears to change text, check the returned value. Usually, you must assign that value to a variable.
public class StringImmutabilityDemo {
public static void main(String[] args) {
String message = "Hello, Java";
String shorter = message.substring(0, 5);
String changed = message.replace("Java", "World");
System.out.println(message); // Hello, Java
System.out.println(shorter); // Hello
System.out.println(changed); // Hello, World
}
}If you write message.replace("Java", "World"); without using the returned value, the operation has no lasting effect on message.
References Can Change
Immutability applies to the object, not to the variable that refers to it. A variable can be reassigned:
String value = "first";
value = "second";No string was modified. The variable value first referred to one String object and then referred to another.
This distinction is important:
- Mutation changes the existing object.
- Reassignment changes which object a variable refers to.
- A
Stringsupports reassignment, but not mutation.
A reference declared with final cannot be reassigned, but the string is still immutable:
final String name = "Ada";
// name = "Grace"; // Does not compilefinal protects the reference held by name. Java's String class protects its own character content independently.
Why Java Uses Immutable Strings
Immutability gives strings several useful properties.
Safe sharing
Many parts of a program can refer to the same string without one part unexpectedly changing another part's data. If a method receives a String, it can safely keep or share that reference.
Stable hash values
Strings are commonly used as keys in hash-based collections such as HashMap. A hash value is calculated from the string's characters. If those characters could change after insertion, the object could become impossible to find in the collection.
Because a string cannot change, its hash value remains stable.
String pooling
Java can reuse identical string literals through a mechanism called the string pool. For example, the runtime may share one object for the literal "ready" used in several places. Sharing is safe because no code can mutate that object.
Security
Strings often hold file names, class names, configuration values, or permission-related data. If a string could change unexpectedly after validation, the program might validate one value and later use another. Immutability removes that particular risk.
The Cost of Repeated Reassignment
Immutability has a performance consequence when a program builds a long result one piece at a time:
String result = "";
for (int i = 0; i < 5; i++) {
result = result + i;
}Each concatenation produces a new string value because the existing result cannot be extended in place. The variable is repeatedly reassigned to newer objects. For a small number of operations, this is clear and acceptable. For large loops, it can create unnecessary allocations and copying.
The next chapter examines that cost in detail and introduces the class designed for efficiently building changing text.
Exercise
After String text = "abc"; String copy = text.replace("a", "x");, what are the values of text and copy, and why?
Show answer
text is "abc" and copy is "xbc". replace returns a new String; it does not mutate the original object.