25

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?

daveslab
  • 10,000
  • 21
  • 60
  • 86
  • Which compiler or tool are you using? – notnoop Jan 08 '10 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". – notnoop Jan 08 '10 at 15:48
  • That is valid, @notnoop. I'm using Eclipse. My language was sloppy. – daveslab Jan 08 '10 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? – notnoop Jan 08 '10 at 15:52

4 Answers4

47

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)

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
8

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.

Ed Altorfer
  • 4,373
  • 1
  • 24
  • 27
  • 1
    Quoting: `To prevent the second, third, and nth conditions from being tested if the first is false`. Actually if the operator is `||` the compiler cannot conclude the overall value from the first alone if the first is false. – H2ONaCl Feb 09 '12 at 07:59
2

James and Ed are correct. If you come across a case in which you would like all expressions to be evaluated regardless of previous failed conditions, you can use the non-short-circuiting boolean operator &.

danben
  • 80,905
  • 18
  • 123
  • 145
1

Yes, Java practices lazy evaluation of if statements in this way. if myString==null, the rest of the if statement will not be evaluated

James B
  • 3,692
  • 1
  • 25
  • 34