Home »
Java Programs »
Java Basic Programs
Java program to demonstrate the example of left shift (<<) operator
Example of left shift (<<) operator: Given a value, we have to perform left shift operation.
Submitted by Nidhi, on March 07, 2022
Problem statement
Left Shift Operator (<<) is a bitwise operator, which operates on bits. It is used to shift a given number of bits in the left and inserts 0's in the right.
In this program, we will demonstrate the use of the left shift (<<) operator and print the result.
Java program to demonstrate the example of left shift (<<) operator
The source code to demonstrate an example of the left shift (<<) operator is given below. The given program is compiled and executed successfully.
// Java program to demonstrate an example
// of left shift (<<) operator
public class Main {
public static void main(String[] args) {
int num = 0xff;
System.out.printf("Number before left shift: %04X\n", num);
//shifting 2 bits left
num = (num << 2);
System.out.printf("Number after left shift: %04X\n", num);
}
}
Output
Number before left shift: 00FF
Number after left shift: 03FC
Explanation
In the above program, we created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we created an integer variable initialized with 0xff. Then we performed left-shift operation and printed the result.
Binary of 0xFF in (in bytes format) - 0000 0000 1111 1111.
After 2 bits left shift (in bytes format) – 0000 0011 1111 1100, which is equivalent of 0x03FC.
Java Basic Programs »