Search code examples
javacastingparentheses

Precedence in expression including parentheses and int cast in java


I have the following expression in my code

int n = ((int) Math.sqrt(4 * 4 + 5) - 1) / 2;

Can someone tell me the precedence in which the expression is evaluated?

Logically I would evaluate the expression in the following way:

  1. 4 * 4 + 5 = 16 + 5 = 21

  2. Math.sqrt(21) ~ 4.58

  3. 4.58 - 1 = 3.58

  4. (int) 3.58 = 3

  5. 3 / 2 = 1.5

However the code evaluates to 1.


Solution

  • You almost got it. The only difference (which doesn't matter for the result) is that the cast is evaluated before the subtraction, and you're using integer division:

    1. 4 * 4 + 5 = 16 + 5 = 21
    2. Math.sqrt(21) ~ 4.58
    3. (int) 4.58 = 4 (cast first)
    4. 4 - 1 = 3
    5. 3 / 2 = 1 (integer division)