Java – Why do we need to use shift operators in java

bit-shiftjava

  1. What is the purpose of using Shift operators rather than using division and multiplication?

  2. Are there any other benefits of using shift operators?

  3. Where should one try to use the shift operator?

Best Answer

Division and multiplication are not really a use of bit-shift operators. They're an outdated 'optimization' some like to apply.

They are bit operations, and completely necessary when working at the level of bits within an integer value.

For example, say I have two bytes that are the high-order and low-order bytes of a two-byte (16-bit) unsigned value. Say you need to construct that value. In Java, that's:

int high = ...;
int low = ...;
int twoByteValue = (high << 8) | low;

You couldn't otherwise do this without a shift operator.

To answer your questions: you use them where you need to use them! and nowhere else.