A common mistake Java novices do is using the == operator to compare Strings. This does almost certainly lead to unexpected and unwanted behaviour. There is a simple solution to this problem and a not so simple explanation why it is such a common mistake.
The simple solution is to use String.equals instead of the == operator.
So when you want to know if two String objects hold the same value instead of
String a = "Test";
String b = "Test";
if (a == b) {
// Do something
} |
String a = "Test";
String b = "Test";
if (a == b) {
// Do something
}
just use this:
String a = "Test";
String b = "Test";
if (a.equals(b)) {
// Do something
} |
String a = "Test";
String b = "Test";
if (a.equals(b)) {
// Do something
}
But look out for null Strings, == handles null Strings nicely but when you call
String a = null;
String b = "Test";
if (a.equals(b)) {
// Do something
} |
String a = null;
String b = "Test";
if (a.equals(b)) {
// Do something
}
it will result in a NullPointerException!
Continue reading