Java bit operations — which two expressions evaluate to the same result?\n\nExpressions:\n1) 32/4\n2) (8 >> 2) << 4\n3) 2^5\n4) 128 >>> 2\n5) 2 >> 5\n\nAssume int arithmetic and default operator precedence.

Difficulty: Easy

Correct Answer: 2 and 4

Explanation:


Introduction / Context:
This item tests knowledge of shift operators and clarifies that ^ is bitwise XOR, not exponentiation. You must determine which pair among the given expressions yields the same integer result.



Given Data / Assumptions:

  • 32-bit signed int arithmetic.
  • >> is arithmetic right shift; << is left shift; >>> is logical right shift; ^ is XOR.


Concept / Approach:
Evaluate each expression explicitly. Compare the results to find equal pairs. Note that right-shifting 128 by 2 places (logical) gives 32. Composing shifts on 8 as shown produces another constant you can compute directly.



Step-by-Step Solution:

1) 32/4 = 8.2) (8 >> 2) << 4 → 8 >> 2 = 2; then 2 << 4 = 32.3) 2 ^ 5 → XOR of 2 and 5 = 7.4) 128 >>> 2 → logical right shift 128 by 2 = 32.5) 2 >> 5 → arithmetic right shift gives 0.Equal pair: expressions 2 and 4 (both 32).


Verification / Alternative check:
Quick mental binary: 128 is 1 at bit 7; shifting right 2 → bit 5 set → 32. For expression 2, 8 (bit 3) >> 2 → bit 1 (value 2); << 4 → bit 5 (value 32).



Why Other Options Are Wrong:

  • Pairs including 1 or 5 do not match 32.
  • Pair including 3 assumes XOR equals exponent; it does not.


Common Pitfalls:
Confusing ^ with power and overlooking that logical vs arithmetic right shifts differ only for negative operands.



Final Answer:
2 and 4

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion