My Java program needed to determine whether a particular variable was null. I wasn't getting the expected results, so I added a System.out.println call to print some diagnostic output to the console. The diagnostic output wasn't what I expected, either. It turned out to have to do with
operator precedence in Java. Here's some example code that illustrates the problem:
public class Example {
public static void main(String[] args) {
Integer n = 1;
System.out.println("Is n null? " + n == null);
}
}
I expected the output to be:
Is n null? false.
Instead, it was just the single word
false. Here's why:
The additive operator + has higher precedence than the equality operator ==. So Java was evaluating the string concatenation
"Is n null? " + n
and then comparing the result to
null. The result of that comparison was the boolean value
false, which is what was displayed. This was easily fixed with the addition of a couple of parentheses:
System.out.println("Is n null? " + (n == null));
Interestingly, if I'd been comparing n to some integer rather than to
null, the compiler would have caught the problem for me. This code
public class Example {
public static void main(String[] args) {
Integer n = 1;
System.out.println("Is n one? " + n == 1);
}
}
causes a compile-time error,
Incompatible operand types String and int.
The moral of the story is, whatever language you're programming in, be aware of operator precedence!