Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the priority of casting in java?

Tags:

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 

?

like image 488
Avi Mosseri Avatar asked May 05 '14 02:05

Avi Mosseri


People also ask

Which operator has the highest priority in Java?

The operator precedence is responsible for evaluating the expressions. In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

What is operator priority in Java?

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

What is the importance of casting in Java?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.


1 Answers

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.

like image 152
Max Roncace Avatar answered Dec 04 '22 04:12

Max Roncace