«^»
3.4. Changing a String object

The class java.lang.String is rather unusual: none of its methods alter the object to which the method is being applied. The objects of the class are said to be immutable.

Instead of a method altering the value of a string object, it will produce a new string object. For example, consider:

String tToday = new String("1999-07-11");
tToday = tToday.replace('-', ':');
System.out.println(tToday);
First, a string object containing the string "1999-07-11" is created and tToday is made to point to it. Then the method replace is applied to the string object that is pointed to by tToday. This does not change that string object, but instead creates a new string object in which any occurrences of the '-' character are replaced by a ':' character. Then the value of tToday is changed. It is currently pointing to the first string object, and it is now altered to point to the new string object. There is now no variable pointing to the first string object: it is lost. Finally, the string that tToday points to is output by the call of the println method:
1999:07:11