Possible Duplicate:
&& (AND) and || (OR) in Java IF statements
This is a question I should have probably known the answer to years ago but if I am writing an if statement in Java that has something like if(x != null && y == null && x.equals(z)) is this safe? I assume that the if statement cond开发者_运维百科itions are interpreted from left to right so checking if x != null to begin with will assure no null pointer exception is thrown (at least by x) on the x.equals(z) part of the condition. Is this accurate?
Yes. It's called short-circuited logic: http://en.wikipedia.org/wiki/Short-circuit_evaluation.
like @mellamokb said it's short circuit.
I only add that if you have comparasion like that:
if (str != null && str.equals("FINAL STRING") {...}
better use:
if ("FINAL STRING".equals(str)) {...}
first way is very often choosen but conditions should be as simple as possible:)
The short answer: You're just fine doing that.
The long answer: You're just fine doing that, because Java uses something called short circuit boolean evaluation. Read about it here
Short and simple: Yes, that is correct. :)
精彩评论