2

The following expression evaluates to 14.

    int a=4;
    int b=6;
    int c=1;
    int ans= ++c + b % a - (c - b * c);
    System.out.print(ans);

This is how i calculate this

    1. (c - b * c) // since bracket has highest preference
    ans : -5
    2. ++c //since unary operator has next highest preference
    ans : 2
    3. b%a // % has higher preference than + and -
    ans : 2

Therefore, 2 + 2 - (-5) = 9

As you can see I'm getting 9 as the value. Not sure what's wrong in my way of calculation (pretty sure I'm gonna end up looking stupid)

Edit : I refered to the below link for precedence and association. https://introcs.cs.princeton.edu/java/11precedence/

Can someone explain the difference between level 16 and level 13 parentheses? I thought level 13 parentheses is used only for typecasting. That is why i considered level 16 parenthesis for evaluating the expression.

Rosily
  • 87
  • 1
  • 2
  • 7
  • https://stackoverflow.com/questions/6373976/precedence-of-and-operators-in-java check this one and the javadoc: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – ItFreak Sep 13 '19 at 13:18
  • 2
    Evaluation order is not the same as precedence. [Java *always* evaluates left-to-right](https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.7). Precedence then describes how the values are combined. – Andy Turner Sep 13 '19 at 13:18
  • Specifically this is the same as doing `int ans = 2 + 6 % 4 - (2 - 6 * 2);` if you want to compare to the real math equation. – Nexevis Sep 13 '19 at 13:21
  • Ignore my now deleted comment. `++` is indeed executed first, even though parenthesis have a [higher operator precedence](https://introcs.cs.princeton.edu/java/11precedence/). See @AndyTurner's comment and answer for clarification on the left-to-right evaluation. – Kevin Cruijssen Sep 13 '19 at 13:30

2 Answers2

5

Evaluation order is not the same as precedence. Java always evaluates left-to-right (with a minor caveat around array accesses).

Effectively, you are evaluating the following expression, because the very first thing that happens is the pre-increment of c:

2 + 6 % 4 - (2 - 6 * 2)

Precedence then describes how the values are combined.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

As you are using pre-increment operator on c. So, after applying increment on c the value of c will be 2. Now :

(c - b * c) will be evaluated to (2 - 6 * 2)= -10

So, the final expression will be 2 + 2 - (-10) = 14

Amit Bera
  • 7,075
  • 1
  • 19
  • 42