Java Bitwise Shift Operators
Overview
In this tutorial, let’s discuss Java bitwise shift operators with some examples. Shifting means moving the operand bits to the left or right depending upon the kind of shift operator. i,e one bit moves forward or backward making space for the next bit to take its place.
Right Shift Operator
The right shift operator (>>) shifts the bits to the right by a specified number of positions. The number of positions up to which the shifting should occur is given as the parameter after the operator. When shifting right >>, the lost bits are filled in which previous leftmost bits.
To understand right shift operator more clearly, let’s understand with an example:
int x =14;
The 32 bit binary equivalent of the number x is:
00000000 00000000 000000000 00001110
Shifting the number x right 2 times x >> 2, the output we get is:
00000000 00000000 00000000 00000011 ( 3)
Left Shift Operator
The left shift operator( <<) shifts the bits to the left by a specified number of positions. The void left behind by the shift is filled by zeros and the lost bits are filled in with previous rightmost bits.
int y = 6;
The 32 bit binary equivalent of the number y is:
00000000 00000000 000000000 00000110
Shifting the number y left 3 times y << 3, the output we get is:
00000000 00000000 000000000 00110000 ( 48)
Code Example
Now let’s create a simple program to demonstrate the bitwise logical operators.
/* * Java Program to demonstrate * Bitwise Shift Operators. * Java Tutorials -- www.TestingDocs.com */ public class BitwiseShiftOperator { public static void main(String args[]) { //Declare two variables int x =14; int y = 6; System.out.println("x=: " + x); System.out.println("y=: " + y); // Bitwise Right Shift operation System.out.println("Right Shift x >> 2 is:= " + (x >> 2)); // Bitwise Left Shift operation System.out.println("Left Shift y << 3 is:= " + (y << 3)); } }
Output
x=: 14
y=: 6
Right Shift x >> 2 is:= 3
Left Shift y << 3 is:= 48
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :