51. Revealing a common mistake with Strings
Everybody knows that String
is an immutable class.
Even so, we are still prone to accidentally write code that ignores the fact that String
is immutable. Check out this code:
String str = "start";
str = stopIt(str);
public static String stopIt(String str) {
str.replace(str, "stop");
return str;
}
Somehow, it is logical to think that the replace()
call has replaced the text start with stop and now str
is stop. This is the cognitive power of words (replace is a verb that clearly induces the idea that the text was replaced). But, String
is immutable! Oh… we already know that! This means that replace()
cannot alter the original str
. There are many such silly mistakes that we are prone to accidentally make, so pay extra attention to such simple things, since they can waste your time in the debugging stage.
The solution is obvious and self-explanatory:
public static String stopIt(String str) {
str = str.replace(str, "stop");
return str;
}
Or, simply:
public static String stopIt(String str) {
return str.replace(str, "stop");
}
Don’t forget that String
is immutable!