This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# operators

matt love
Ranch Hand
Posts: 67
from K & B book page 417:

Would someone explain to me how this breaks down, that is, how to approach solving it:

(x > 4 && x < 8)

Thanks.

Matt

Dan Drillich
Ranch Hand
Posts: 1183
&& says -

false && false -> false
false && true -> false
true && false -> false
true && true ->

So, in this case it would return true when x is bigger than 4 and lower than 8, false otherwise.

Regards,
Dan

matt love
Ranch Hand
Posts: 67
Thanks Dan.

So, it sounds like your saying (x > 4 && x < 8) is the same as ((x > 4) && (x < 8))?

Without parentheses it would seem to me if you evaluate left to right, you'd evaluate "x > 4", let's say true, then evaluate "true && x" where x is some int and you'd get a compiler error because an int does not resolve to a boolean. Where do I go haywire?

Thanks.

Matt

Dan Drillich
Ranch Hand
Posts: 1183
Hi Matt, it's about Operator Precedence.

< and > take precedence over &&.

Regards,
Dan

Matthew Brown
Bartender
Posts: 4565
8
There's an order of precedence of operators in Java (and most other languages). Operators with higher precedence get applied first regardless of the order they appear - unless you use brackets to force a particular order.

For a possibly more familiar example, what would you expect (1 + 2*3) to be? The * has higher precedence than +, so it's 7, not 9.

Another example: = is actually an operator. If it wasn't for the rules of precedence, something as straightforward as x = a + 1 really wouldn't do what you'd expect (think about what the effect is if you applied that left-to-right).

See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html for the full rules of precedence.

As a rule, though, when writing code if you have any confusion as to what the order will be, add brackets to make it clearer, even if they aren't strictly needed.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?