Why are Strings immutable in Java, and what practical benefits does that give you?
A String cannot be changed once it has been made. Every method that looks like it changes the text actually builds a brand new string and gives it back to you.
That sounds inconvenient, but it buys four real benefits.
It is safe to share. If you pass a string to another method, that method cannot change it behind your back. You do not have to make a copy to protect yourself, and you do not have to think about whether the other method will change it.
It is safe to use as a key in a map. A hash map works out where to put a key by using its value. If the value could change while the key was in the map, the map would be broken, because the key would no longer be in the place where it was put. Because a string never changes, this problem cannot happen.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> capitals = new HashMap<String, String>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");
String key = "France";
System.out.println("value : " + capitals.get(key));
// Changing the string makes a new object, so the map still works.
key = key + " and Spain";
System.out.println("new value : " + capitals.get(key));
System.out.println("old key : " + capitals.get("France"));
// A string can safely be shared between threads.
String shared = "shared value";
String first = shared;
String second = shared;
System.out.println("same object : " + (first == second));
}
}
It is safe to use in a constant. A constant is a value that is written down once and read many times, and the compiler can share one copy of it between every place that uses it, because nothing can change it.
It is safe to use with the constant pool. That is the subject of a later question in this topic.
The next question in this topic looks at what actually happens when you try to change a string.