17.2: Strings Are Immutable
- Page ID
- 15264
Strings provide methods, toUpperCase
and toLowerCase
, that convert from uppercase to lowercase and back. These methods are often a source of confusion, because it sounds like they modify strings. But neither these methods nor any others can change a string, because strings are immutable.
When you invoke toUpperCase
on a string, you get a new string object as a return value. For example:
String name = "Alan Turing"; String upperName = name.toUpperCase();
After these statements run, upperName
refers to the string "ALAN TURING"
. But name
still refers to "Alan Turing"
.
Another useful method is replace
, which finds and replaces instances of one string within another. This example replaces "Computer Science"
with "CS"
:
String text = "Computer Science is fun!"; text = text.replace("Computer Science", "CS");
This example demonstrates a common way to work with string methods. It invokes text.replace
, which returns a reference to a new string, "CS is fun!"
. Then it assigns the new string to text
, replacing the old string.
This assignment is important; if you don’t save the return value, invoking text.replace
has no effect.