Friday, 10 September 2010

Strings are immutable

Sometimes I come across something like this:
String myString = "Jack";

// Concatenates the specified string to the end of this string.
// (taken directly from JavaDoc)
myString.concat(" and the Beanstalk");

And people are very surprised when they see that the String myString has not been changed.

It is very confusing, the javadoc helps if you've noticed that a new String is returned by the concat method. Strings cannot be changed! Therefore, either use StringBuffer or be prepared to create a huge pile of new String objects.

No comments:

Post a Comment