Sub topic 1
Why Strings Are Immutable
Prerequisites
This chapter assumes basic Java syntax, loops, methods, and familiarity with String and the + operator. You should also know that objects and primitive values behave differently.
Why Strings Are Immutable
A String is immutable, which means its character content cannot change after the object is created. Methods such as toUpperCase() return a new String instead of changing the original.
String word = "java";
String upper = word.toUpperCase();
System.out.println(word); // java
System.out.println(upper); // JAVAImmutability makes strings safe to share. If several variables refer to the same string, one part of a program cannot change the characters seen by another part. Immutable strings can also be cached and safely used as keys in hash-based collections.
The Cost of Concatenating in a Loop
The + operator creates a new string when it combines strings. The existing string remains unchanged.
String s = "";
for (int i = 0; i < 5; i++) {
s += i;
}
System.out.println(s); // 01234Each iteration creates a new String containing the old characters and the new value. As the accumulated text grows, Java repeatedly copies that text. For a long loop, this can create many temporary objects and unnecessary copying.
The process can be viewed like this:
Building Strings with StringBuilder
StringBuilder is a mutable object designed for changing character sequences. Its append method adds text to the same builder. Call toString() when the final immutable String is needed.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append("Item ").append(i).append('\n');
}
String result = sb.toString();
System.out.print(result);
}
}append returns the same builder, so calls can be chained. The builder grows an internal buffer instead of creating a new String for every append. This usually makes it the better choice for assembling text in loops.
Exercise
Why does StringBuilder usually perform better than String concatenation in a long loop?
Show answer
StringBuilder changes one mutable buffer, while repeated concatenation creates new strings and copies the accumulated characters.