Avi Mosseri
Avi Mosseri

Reputation: 1368

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

?

Upvotes: 31

Views: 20507

Answers (1)

Max Roncace
Max Roncace

Reputation: 1262

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.

Upvotes: 36

Related Questions