Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 10>>2+5>>2 evaluate to zero?

Tags:

java

operators

Consider the following code:

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

When run, the (surprising) output is 0.

Why is it so?

like image 315
visweswara rao Lolugu Avatar asked Apr 26 '26 23:04

visweswara rao Lolugu


2 Answers

Taking Java's operator precedence (notably that + has higher precedence than >>) and associativity rules into account, the expression is equivalent to

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

or

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

which is zero.

If you need the shifts to happen before the addition, parenthesise them:

(a >> 2) + (b >> 2)
like image 116
NPE Avatar answered Apr 28 '26 11:04

NPE


Because it's like writing (Operator Precedence):

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

Which is like writing:

(10 >> 7) >> 2

Which is 0. Why?

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

00001010

Now, shift it right by 7 and you'll get 0. Shift it right by 2, you'll still get 0.

like image 21
Maroun Avatar answered Apr 28 '26 11:04

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!