Demonstrate Left Shift in Java
Problem
The left shift operator (<<) moves every bit of a number to the left by a given count, filling the vacated positions on the right with zeros — each single shift is equivalent to multiplying by 2.
Given an integer, shift its bits left by a given count and show the binary form before and after.
Java Program
public class DemonstrateLeftShift {
public static void main(String[] args) {
int a = 5;
int shiftBy = 2;
int result = a << shiftBy;
System.out.println("a = " + a + " (" + Integer.toBinaryString(a) + ")");
System.out.println("a << " + shiftBy + " = " + result + " (" + Integer.toBinaryString(result) + ")");
}
}Output
Core Logic
Shifting a's bits left by 2 positions appends two zero bits on the right, which is the same as multiplying a by 2 twice.
- 1
Integer.toBinaryString(a)shows5as101in binary. - 2
a << 2moves every bit two positions to the left, dropping any bits that fall off the left edge and filling the two newly-vacated positions on the right with0. - 3
101shifted left by 2 becomes10100. - 4
10100in binary is20in decimal — the same result as5 * 2 * 2, since each left shift doubles the value.
5 (101) shifted left by 2 gives 10100, or 20 — the same as 5 * 4.Key Point: n << k is a fast, exact equivalent of n * 2^k for non-negative shift counts that don't overflow — a common low-level optimization, though on modern JVMs the compiler often performs this same optimization automatically.
Key Concepts
Approach 2: Java 8
import java.util.function.IntBinaryOperator;
public class LeftShiftLambda {
public static void main(String[] args) {
int a = 5;
int shiftBy = 2;
// The << logic is stored as a named, reusable lambda
IntBinaryOperator leftShift = (x, y) -> x << y;
int result = leftShift.applyAsInt(a, shiftBy);
System.out.println("a = " + a + " (" + Integer.toBinaryString(a) + ")");
System.out.println("a << " + shiftBy + " = " + result + " (" + Integer.toBinaryString(result) + ")");
}
}
Output
Core Logic
Wrapping << in a named IntBinaryOperator turns 'shift this int left by this many bits' into a reusable value instead of a one-off inline expression.
- 1
IntBinaryOperator leftShift = (x, y) -> x << y;stores the left-shift logic as a lambda. - 2
leftShift.applyAsInt(a, shiftBy)calls it withaandshiftBy, returning the same resulta << shiftBywould inline. - 3The binary strings are built exactly as before, with
Integer.toBinaryString().
a = 5 and shiftBy = 2, leftShift.applyAsInt(5, 2) returns 20, same as a << shiftBy.Key Point: Naming the lambda leftShift makes it clear at the call site what operation it performs — the same pattern used for the arithmetic and bitwise operator pages.