Java short circuit evaluation

Donnie picture Donnie · Nov 29, 2009 · Viewed 10.2k times · Source

I thought Java had short circuit evaluation, yet this line is still throwing a null pointer exception:

if( (perfectAgent != null) && (perfectAgent.getAddress().equals(entry.getKey())) ) {

In this case perfectAgent is null, so I just want the whole expression to return false, but my app is still crashing on this line with a NullPointerException.

EDIT, general response:

Since perfectAgent is null, nothing to the right of the && should be executed, as it is impossible for the expression to be true. More to the point, it is impossible to execute perfectAgent.getAddress() since perfectAgent does not contain a valid reference (it being null and all). I'm trying to use short circuit evaluation to not have to check for null in a seperate statement as that makes the logic more sloppy.

EDIT 2 (or, I'm an idiot): Yeah, like many things in life you figure out the answer right after announcing to the world that you're a moron. In this case, I had turned off Eclipse's autobuild while doing something else and not turned it back on, so I was debugging class files that didn't match up with my source.

Answer

Jon Skeet picture Jon Skeet · Nov 29, 2009

If perfectAgent is genuinely null, that code won't throw an exception (at least assuming there aren't weird threading things going on, changing it from non-null to null half way through the expression). I would be utterly shocked if you could produce a short but complete program demonstrating it doing so.

So yes, your intuition is right - this shouldn't be a problem. Look elsewhere for the cause. I strongly suspect that perfectAgent isn't actually null, and that you're running into any of the other situations in that code which could cause an exception.

I suggest you try to extract that bit of code out into a short but complete example - if you can do so, I'll eat my metaphorical hat; if not, you'll hopefully find the problem while you attempt the extraction.

What makes you think that perfectAgent really is null? Try inserting this code before it:

if (perfectAgent == null)
{
    System.out.println("Yup, it's null");
}

Another very, very slim possibility is that you've run into a JIT bug - but I highly doubt it.