0

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 conditions 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?

Community
  • 1
  • 1
thurmc
  • 495
  • 1
  • 8
  • 29
  • Such things are best checked by [consulting the JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23). It is very strict, precise and is available for free, not like C++. – Sergei Tachenov Feb 17 '11 at 18:16
  • 2
    @Sergey: But it's a lot easier to ask on stackoverflow.com and get 4 answers in 2 minutes. – mellamokb Feb 17 '11 at 18:20

4 Answers4

4

Yes. It's called short-circuited logic: http://en.wikipedia.org/wiki/Short-circuit_evaluation.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
1

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:)

lukastymo
  • 26,145
  • 14
  • 53
  • 66
0

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

Dave McClelland
  • 3,385
  • 1
  • 29
  • 44
0

Short and simple: Yes, that is correct. :)