Why Strings Are Immutable
Understand string immutability.
Strings Cannot Change
In Java a String is immutable: once created, its characters can never change. Any method that seems to modify a string actually returns a brand new string.
Methods Return New Strings
toUpperCase(), replace(), and friends do not alter the original. They produce a new String and leave the original untouched.
public class Main {
public static void main(String[] args) {
String original = "hello";
String upper = original.toUpperCase();
System.out.println("original: " + original);
System.out.println("upper: " + upper);
}
}All lessons in this course
- Why Strings Are Immutable
- Building Strings with StringBuilder
- StringBuilder Methods
- StringBuilder vs StringBuffer