Java Language Pitfall: Not understanding that String is an immutable class


Example

New Java programmers often forget, or fail to fully comprehend, that the Java String class is immutable. This leads to problems like the one in the following example:

public class Shout {
    public static void main(String[] args) {
        for (String s : args) {
            s.toUpperCase();
            System.out.print(s);
            System.out.print(" ");
        }
        System.out.println();
    }
}

The above code is supposed to print command line arguments in upper case. Unfortunately, it does not work, the case of the arguments is not changed. The problem is this statement:

s.toUpperCase();

You might think that calling toUpperCase() is going to change s to an uppercase string. It doesn't. It can't! String objects are immutable. They cannot be changed.

In reality, the toUpperCase() method returns a String object which is an uppercase version of the String that you call it on. This will probably be a new String object, but if s was already all uppercase, the result could be the existing string.

So in order to use this method effectively, you need to use the object returned by the method call; for example:

s = s.toUpperCase();

In fact, the "strings never change" rule applies to all String methods. If you remember that, then you can avoid a whole category of beginner's mistakes.