Boolean expression order of evaluation in Java?

daveslab picture daveslab · Jan 8, 2010 · Viewed 20k times · Source

Suppose I have the following expression

String myString = getStringFromSomeExternalSource();
if (myString != null && myString.trim().length() != 0) {
...
}

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?

Answer

Prasoon Saurav picture Prasoon Saurav · Jan 8, 2010

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)