Skip to main content
Immutability · Topic 6 of 6

String immutability

Definition​

A Java String can never be changed after it is created. Methods like toUpperCase() or replace() return a new String and leave the original alone. Use StringBuilder when you build text in a loop.

Example code​

String methods return new strings; StringBuilder changes in place

class Demo {
public static void main(String[] args) {
String name = "asha";
name.toUpperCase(); // result thrown away: name is unchanged
System.out.println(name);

String upper = name.toUpperCase(); // keep the new String
System.out.println(upper);

StringBuilder builder = new StringBuilder(); // mutable, ideal for loops
for (int i = 1; i <= 3; i++) builder.append(i).append(' ');
System.out.println(builder.toString().trim());
}
}

// Output:
// asha
// ASHA
// 1 2 3

Finished this page? Track your progress (saved only in your browser).