The numberOfLeadingZeros() method of Integer class, returns number of 0’s bits before the first one-bit in the binary representation of the given int number. If number is zero (there are no one-bit), then it returns 32.
Syntax of numberOfLeadingZeros() method
public static int numberOfLeadingZeros(int i)
numberOfLeadingZeros() Parameters
i– An int value whose number of leading zeroes needs to be determined.
numberOfLeadingZeros() Return Value
- Returns number of zero bits preceding the highest-order (leftmost) one bit
Supported versions: Java 1.5 and onwards.
Example 1
Here, we are counting the number of zero bits before first one-bit in the given number. The point to remember is that each number is represented as 32 bits binary number. The binary representation of decimal number 20 is 10100, however when this is represented as a 32 bits binary number then it is proceeded with 27 zero bits.
This is why this method returns 32 for the integer value 0 as all 32 bits are zeroes.
class JavaExample {
public static void main(String args[]) {
//binary equivalent:
// 0000 0000 0000 0000 0000 0000 0001 0100
int i = 20;
System.out.print("Number of leading zero bits: ");
System.out.print(Integer.numberOfLeadingZeros(i));
}
}
Output:

Example 2
The number of leading zeroes are returned as zero for the negative numbers as the most significant bit is 1 for negative numbers.
class JavaExample {
public static void main(String args[]) {
//MSF (Most significant bit) is 1
int i = -100;
System.out.print("Number of leading zero bits: ");
System.out.print(Integer.numberOfLeadingZeros(i));
}
}
Output:
