Why is the score 10 >> 2 + 5 >> 2 zero?

Consider the following code:

int a=10, b=5;
int c=a>>2+b>>2;
System.out.println(c);

      

On startup, the (awesome) output is 0.

Why is this so?

+3


source to share


3 answers


Taking Java operator precedence (specifically, which +

has higher precedence than >>

) and associativity rules, this expression is equivalent to

(a >> (2 + b)) >> 2

      

or

(10 >> (2 + 5)) >> 2

      



which is zero.

If you need shifts to happen before addition, put them in parentheses:

(a >> 2) + (b >> 2)

      

+5


source


Because he likes to write (Operator Precedence) :

(a >> (2 + 5)) >> 2

      

As written:

(10 >> 7) >> 2

      



What is 0. Why?

Think of the binary representation of 10, assuming 8-bit:

00001010

      

Now move it to the right by 7 and you get 0. Move it to the right by 2, you still get 0.

+2


source


Operator priority!

If your code can be interpreted differently, it will almost certainly be one day. Always use parentheses - never rely on operator precedence.

    int a = 10, b = 5;

    int c = a >> 2 + b >> 2;
    System.out.println(c);
    int d = (a >> 2) + (b >> 2);
    System.out.println(d);
    int e = ((a >> 2) + b) >> 2;
    System.out.println(e);
    int f = a >> (2 + b) >> 2;
    System.out.println(f);

      

prints

0
3
1
0

      

0


source







All Articles