27

if I have a line of code that goes something like

int s = (double) t/2   

Is it the same as

int s = (double) (t/2)

or

int s = ((double) t)/2

?

Avi Mosseri
  • 1,196
  • 1
  • 15
  • 33
  • possible duplicate of [Java operator precedence guidelines](http://stackoverflow.com/questions/2137690/java-operator-precedence-guidelines) – Matt Ball May 05 '14 at 02:52
  • http://stackoverflow.com/questions/5762270/java-casting-order – knoight May 05 '14 at 03:04

1 Answers1

28

This should make things a bit clearer. Simply put, a cast takes precedence over a division operation, so it would be the same thing as give the same output as

int s = ((double)t) / 2;

Edit: As knoight has pointed out, this is not technically the same operation as it would be without the parentheses, since they have a priority as well. However, for the purposes of this example, it will offer the same result, and is for all intents and purposes equivalent.

Max Roncace
  • 1,197
  • 2
  • 15
  • 39
  • 3
    parentheses override precedence - so it's not quite the same. – knoight May 05 '14 at 03:03
  • 3
    @knoight What I meant was, while it's technically a different operation, the override doesn't change the priorities, so it's a fair comparison. – Max Roncace May 05 '14 at 20:42
  • You're correct that in this particular example the parentheses have no effect on the end result - however the point I wanted to make was that parentheses do affect the order of evaluation. So if the OP had chosen a different example, such as the one in the link I posted above, then the placement of parentheses becomes very important - and I feel that was overlooked in your answer. An edit touching on evaluation changes my vote – knoight May 06 '14 at 13:55
  • @knoight I've made an edit noting that it's not quite the same thing. I hope it suffices. – Max Roncace May 06 '14 at 19:37