This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

operators

 
matt love
Ranch Hand
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
&& 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Matt, it's about Operator Precedence.

< and > take precedence over &&.

Regards,
Dan
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic