Boolean Expressions

13. Either Order (usually)


    age >= 21 && age <= 35

Either Order (usually)

In most situations, the operands of AND can be in either order. The following

age >= 21 && age <= 35 

is the equivalent of this:

age <= 35 && age >= 21 

One false is enough to make the entire expression false, regardless of where the false occurs.

Warning: If a boolean expression includes an assignment operator or method calls, then the order sometimes does matter. The reason for this involves the short-circuit optimization mentioned previously. Mostly you don't need to worry about this, but make a mental note about this potential problem.

One of the next chapters describes this situation in detail. For the examples in this chapter, the order of operands does not matter.

Question 13:

Examine this expression:

    ( Monster.isAlive() && (hitpoints = Hero.attack()) < 50 )

Do you suspect that the order of operands in this expression matters?