Georgi Velev
Georgi Velev

Reputation: 166

How Java Operator Precedence exactly work?

I want to ask something simple.

I provide a very simple calculation example that I receive a result different than my expectations. Could somebody explain which step I made wrong?

public static void main(String[] args) {
       int x  =1;
       int y = 101;
       int a = 2;


       int z =  ++y + y * a << 3 *2 * ++x + (x+=2);
       /*
       Step 1 int z =  ++y + y * a << 3 *2 * ++x + (3);
       Step 2 int z =  102 + 102 * 2 << 3 *2 * 4 + (3);
       Step 3 int z =  102 + 204 << 24 + (3);
       Step 4 int z =  306 << 27;
       Expected:41,070,624,768‬
        */

       System.out.println(z);
       //Actual: 20,054,016
   }

Upvotes: 0

Views: 81

Answers (1)

rgettman
rgettman

Reputation: 178253

The bit-shift operators have a lower precedence than additive operators, which have a lower precedence than multiplicative operators, which have a lower precedence than increment/decrement operators. Also notice that variables are evaluated left-to-right regardless of the precedence of the operators between them.

int z =  ++y + y * a << 3 *2 * ++x + (x+=2);

First, do increments.

102 + 102 * 2 << 3 * 2 * 2 + 4

Next, do multiplication.

102 + 204 << 12 + 4

Then do addition.

306 << 16

The bit shift results in 20054016.

It looks like you erred when evaluating the expressions with x in them on the far right.

Upvotes: 1

Related Questions