Java Notes
A Java String cannot be changed after it is created. Concatenation, replacement, and case conversion produce a new String and leave the old value intact.
An immutable object cannot change after it is created. String is immutable: Java never edits the characters inside an existing String. Instead, an operation returns a new String.
See immutability in action
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
concat() does not change greeting. It creates a second value and stores that value in updatedGreeting. The same rule applies to replace(), toUpperCase(), trim(), and most other String methods.
Why Java keeps String immutable
- Safe sharing: multiple variables can use the same literal from the String Pool without one part of a program changing text used elsewhere.
- Security: text used for file paths, URLs, class names, and database settings cannot be altered after it is handed to another API.
- Thread safety: read-only objects are safe to share between threads without locks.
- Reliable hash keys: a String used as a
HashMapkey keeps the same content and hash code.
Reassignment is not mutation
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The variable status is reassigned to another String. Java did not modify the characters in "Draft"; that earlier object still exists until it is no longer needed.
Use StringBuilder for repeated changes
Creating a few new Strings is clear and inexpensive. Creating thousands inside a loop is wasteful because each + can create temporary objects. Use StringBuilder when text is assembled step by step.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
append() changes the StringBuilder object in place. Call toString() when you need an immutable String result.
Continue the lesson path