Tuesday, April 15, 2014

How to check if my string is equal to null?

How to check if my string is equal to null?


Solution:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}
Usage:
if (isEmpty(string)) {
  // do something
}
Explanation:
As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.
As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).