Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
When your Java programs start to get big, you’ll inevitably end up with lots and lots of String objects. For security purposes, and for the sake of conserving memory (remember your Java programs can run on teeny Java-enabled cell phones), Strings in Java are immutable. What this means is that when you say:
String s = "0"; for (int x = 1; x < 10; x++) { s = s + x; }
What’s actually happening is that you’re creating ten String objects (with values “0”, “01”, “012”, through “0123456789”). In the end s is referring to the String with the value “0123456789”, but at this point there are ten Strings in existence!
Whenever you make a new String, the JVM puts it into a special part of memory called the ‘String Pool’ (sounds refreshing doesn’t it?). If there is already a String in the String Pool with the same value, the JVM doesn’t create a duplicate, it simply refers your reference variable to the existing entry. The JVM can get away with this because Strings are immutable; one reference variable can’t change a String’s value out from under another reference variable referring to the same String.