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!
No comments:
Post a Comment