I got hung up today on a silly, stupid problem that took me an inordinately long time to track down. It came on a piece of Java code like this:
When that code executed, and the function
Integer x = test() ? 0 : null;
test()returned false, it generated a
NullPointerException. Can you guess what the problem was? It turns out to be the zero! Apparently the type of the result of a conditional expression is determined by the first operand after the "?". In this case, that's an
int– so when
test()returned false the program ended up trying to assign
int, and of course that isn't going to work all that well. I'm a little surprised that the result was a
NullPointerExceptioninstead of some more illuminating exception, but whatever. All I had to do to fix the problem was to change the zero to either
(Integer) 0. After that change, all was well. I'm not the first to run into this problem, of course.
I'm very glad to have that stupid little bug behind me!
Post a Comment