Pitfall Not understanding that String is an immutable class

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Common Pitfalls:
* Pitfall Not understanding that String is an immutable class

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
93 Common Pitfalls
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap