Search code examples
javacasting

What is the priority of casting in java?


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

?


Solution

  • See this table on operator precedence to make things clearer. Simply put, a cast takes precedence over a division operation, so it would give the same output as

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

    As knoight 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.