Java Integer Numberofleadingzeros Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn about the numberOfLeadingZeros() method of the Integer class in Java. This method is used to return the number of zero bits that are preceding the highest-order one bit (leftmost) of the two's complement of the int value passed as an argument.

Create a Java file

Open a terminal and create a new Java file using the following command:

touch ~/project/NumberOfLeadingZerosDemo.java

Implement the numberOfLeadingZeros() method

In the editor, add the following code to implement the numberOfLeadingZeros() method:

public class NumberOfLeadingZerosDemo {
      public static void main(String[] args) {
         int num = 170;
         System.out.format("The number of leading zeros in %d is %d%n", num, Integer.numberOfLeadingZeros(num));
      }
}

This code initializes a variable num with the value 170 and then uses the numberOfLeadingZeros method to return the number of leading zeros in num.

Implement the method with negative numbers

Now, let's modify the program to work with a negative number. Add the following code:

int negativeNum = -57;
System.out.format("The number of leading zeros in %d is %d%n", negativeNum, Integer.numberOfLeadingZeros(negativeNum));

This initializes a variable negativeNum with the value -57 and then uses numberOfLeadingZeros() method to return the number of leading zeros in negativeNum.

Compile and run the program with the negative number

Save the changes to the file and compile the program again using the following command: javac ~/project/NumberOfLeadingZerosDemo.java.

Then, run the program again using the following command: java NumberOfLeadingZerosDemo.

The output should look like this:

The number of leading zeros in 170 is 24
The number of leading zeros in -57 is 0

Summary

In this lab, you learned about the numberOfLeadingZeros() method of the Integer class in Java. You saw how to use this method to return the number of zero bits that are preceding the highest-order one bit (leftmost) of the two's complement of an int value passed as an argument. You also saw how to use it with both positive and negative numbers.

Other Java Tutorials you may like