Immutable means that once the state is initialized, there is no way to alter it. The String class is a good example, since as soon as you have created a String object, you won't be able to change the characters the string is made up. Any mutator method you may invoke upon a String object will return the same string object if no change occured or a new String object if some change occured. Also, all wrapper classes (Byte, Short, Integer, Long, Float, Double, Boolean) are immutable, that is, once initialized, there is no way to change their content...
"Test1" and "Test2" are different objects. You just assign s1 to reference a new String object, "Test2". From JSL 3.10.5
Each string literal is a reference (�4.3) to an instance (�4.3.1, �12.5) of class String (�4.3.3). String objects have a constant value.
Joined: Aug 26, 2001
You said that the String-class is immutable this means that once a value is assigned it cannot be changed. But here I assign a value to a string and change it. The following code shows you what I meant:
The output of this code is "true" (i.e. that is s1 still contains the same character sequence) because the invocation to replace returned a new instance of String with the 'T' replaced by an 'r'. All mutator methods of the String class return new String instances whenever a change occured or the same String instance if no change occured. Bottom line: it is not possible to change the content of a String object once it has been initialized. [ July 31, 2002: Message edited by: Valentin Crettaz ]