aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "operators" Watch "operators" New topic
Author

operators

matt love
Ranch Hand

Joined: Jan 25, 2010
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

Joined: Jul 09, 2001
Posts: 1180
&& 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


William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
matt love
Ranch Hand

Joined: Jan 25, 2010
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

Joined: Jul 09, 2001
Posts: 1180
Hi Matt, it's about Operator Precedence.

< and > take precedence over &&.

Regards,
Dan
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4518
    
    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.
 
wood burning stoves
 
subject: operators