You are reminded the String class is immutable. That is why you have to use the assignment.
Kevin P Smith
Joined: Feb 18, 2005
immutable - That is/was the word I was looking for, the object can not be updated once it has been set.
But then I guess that would beg the obvious question... Why not?
Why have the Java guys not shorthanded the String object so that myString.replaceAll("s","X") updates the myString object's values 's' into 'X'. I guess there is a reason they haven't done this but just wonder why. I'd image that the majority of the time, when you're replaceing string values in a String object, you'd want the same object to contain that new value and if you did want the new value to be held in a new object then you could just do something like
String myString = new String("this is a string");
String anotherString = myString.replaceAll("x","X");
to make anotherString 'ThiX iX a Xtring'
As I say, I guess there's a reason they've done it this way.
Cheers again guys, thanks for the quick responses.
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program, since they :
* are simple to construct, test, and use
* are automatically thread-safe and have no synchronization issues
* do not need a copy constructor
* do not need an implementation of clone
* allow hashCode to use lazy initialization, and to cache its return value
* do not need to be copied defensively when used as a field
* make good Map keys and Set elements (these objects must not change state while in the collection)
* have their class invariant established once upon construction, and it never needs to be checked again
* always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
It basically makes the program easier and safer to use and to program. (Correct me if I'm wrong)