Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Pointing out the correct statements (Q.No. 6)
6.
Which two are equal?
  1. 32/4
  2. (8 >> 2) << 4
  3. 2^5
  4. 128 >>> 2
  5. 2 >> 5
1 and 2
2 and 4
1 and 3
2 and 3
Answer: Option
Explanation:

(2) and (4) are correct. (2) and (4) both evaluate to 32. (2) is shifting bits right then left using the signed bit shifters >> and <<. (4) is shifting bits using the unsigned operator >>>, but since the beginning number is positive the sign is maintained.

(1) evaluates to 8, (3) looks like 2 to the 5th power, but ^ is the Exclusive OR operator so (3) evaluates to 7. (5) evaluates to 0 (2 >> 5 is not 2 to the 5th).

Discussion:
6 comments Page 1 of 1.

Shreyas said:   1 decade ago
A normal right shift >> of a negative number will keep it negative. i.e. the sign bit will be retained.

An unsigned right shift >>> will shift the sign bit too, replacing it with a zero bit.

There is no need to have the equivalent left shift because there is only one sign bit and it is the leftmost bit so it only interferes when shifting right.

Essentially, the difference is that one preserves the sign bit, the other shifts in zeros to replace the sign bit.

For positive numbers they act identically.

Parth said:   1 decade ago
>> is signed bitwise operator has same function as >>> unsigned bitwise operator but there is minor difference.

>>:shifts the number to the right without adding 'ZEROS' before shift.ex-8>>2.
1000>>2==10.

>>>:shifts the number to the right by adding 'ZEROS' before shift.ex-8>>2.
1000>>>2==0010.

Parth said:   1 decade ago
In this question statement 2 is (8>>2)<<4.
8==1000 (in binary).
8>>2.
1000>>2==0010.
Then.
0010<<4==100000.
Output-100000.

Statement 4:
128>>2.
10000000>>2==00100000.
Output-100000.
Hence statement 2 & 4 are correct.

V.rama obula reddy said:   1 decade ago
Please give explanation on << >> operators?

Prince said:   1 decade ago
Cheeky one but generally in keyboard 2^5 is read as 2 power 5.

Manish yadav said:   1 decade ago
Describe >>> operator?

Post your comments here:

Your comments will be displayed after verification.