Boolean expression order of evaluation in Java?

Eclipse warns me that myString might be null in the second phrase of the boolean expression. However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java? Or is the order of evaluation not guaranteed?

asked Jan 8, 2010 at 15:41 10.2k 21 21 gold badges 62 62 silver badges 86 86 bronze badges Which compiler or tool are you using? Commented Jan 8, 2010 at 15:45

Well, javac (the most common compiler) doesn't warn about nullness. If "Java warns me that myString might be null", most likely that's a buggy tool. There is no such thing as "java warns".

Commented Jan 8, 2010 at 15:48 That is valid, @notnoop. I'm using Eclipse. My language was sloppy. Commented Jan 8, 2010 at 15:49

In Eclipse, I can only reproduce the warning with an || operation or with 'myString == null'. Are you sure that Eclipse warned against this code snippet?

Commented Jan 8, 2010 at 15:52

4 Answers 4

However, I know some that some compilers will exit the boolean expression entirely if the first condition fails. Is this true with Java?

Yes, that is known as Short-Circuit evaluation.Operators like && and || are operators that perform such operations.

Or is the order of evaluation not guaranteed?

No,the order of evaluation is guaranteed(from left to right)

answered Jan 8, 2010 at 15:44 Prasoon Saurav Prasoon Saurav 92.5k 51 51 gold badges 242 242 silver badges 347 347 bronze badges

Java should be evaluating your statements from left to right. It uses a mechanism known as short-circuit evaluation to prevent the second, third, and nth conditions from being tested if the first is false.

So, if your expression is myContainer != null && myContainer.Contains(myObject) and myContainer is null, the second condition, myContainer.Contains(myObject) will not be evaluated.

Edit: As someone else mentioned, Java in particular does have both short-circuit and non-short-circuit operators for boolean conditions. Using && will trigger short-circuit evaluation, and & will not.