Rosily
Rosily

Reputation: 97

Java Arithmetic expression

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.

Upvotes: 2

Views: 289

Answers (2)

Amit Bera
Amit Bera

Reputation: 7315

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

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140299

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.

Upvotes: 5

Related Questions