Does Java check all arguments in "&&" (and) operator even if one of them is false?

pixel picture pixel · Nov 12, 2010 · Viewed 7.8k times · Source

I have such code:

if(object != null && object.field != null){
    object.field = "foo";
}

Assume that object is null.

Does this code result in nullPointerException or just if statement won't be executed?

If it does, how to refactor this code to be more elegant (if it is possible of course)?

Answer

Michael Lloyd Lee mlk picture Michael Lloyd Lee mlk · Nov 12, 2010

&& does short circuit while & would not.

But with simple questions like this, it is best to just try it (ideone can help when you don't have access to a machine).

&& - http://ideone.com/LvV6w & - http://ideone.com/X5PdU

Finally the place to check for sure would be the JLS §15.23. Not the most easy thing to read, the relevent section states: The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.