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:
Integer x = test() ? 0 : null;
When that code executed, and the function 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 null to an int, and of course that isn't going to work all that well. I'm a little surprised that the result was a NullPointerException instead of some more illuminating exception, but whatever. All I had to do to fix the problem was to change the zero to either new Integer(0) or (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!

No comments:
Post a Comment