Why do we need to use shift operators in java?

Saravanan picture Saravanan · Sep 17, 2011 · Viewed 10.6k times · Source
  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?

Answer

Sean Owen picture Sean Owen · Sep 17, 2011

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.