Java Integer numberOfTrailingZeros Method

JavaJavaBeginner
Practice Now

Introduction

In Java, the NumberOfTrailingZeros() method is used to return the number of zero bits following the lowest-order one bit (rightmost) of the two's complement of the integer value passed as an argument. In other words, it converts the integer value to binary and returns the total number of zero bits following the lowest(rightmost) one bit. This lab will guide you through the process of using NumberOfTrailingZeros() method in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/classes_objects -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/class_methods -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/exceptions -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/modifiers -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/oop -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/user_input -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/wrapper_classes -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/identifier -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/arrays -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/comments -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/data_types -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/operators -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/output -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/strings -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/variables -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} java/system_methods -.-> lab-117726{{"`Java Integer numberOfTrailingZeros Method`"}} end

Create a Java class

Create a Java class named NumberOfTrailingZerosDemo in the ~/project directory using the following command.

vi ~/project/NumberOfTrailingZerosDemo.java

Add code for NumberOfTrailingZeros() method

In this step, we will add the code to use the NumberOfTrailingZeros() Java method in our class.

public class NumberOfTrailingZerosDemo {

    public static void main(String[] args) {
        int i = 170; // positive number
        System.out.println("Original Number is " + i);
        System.out.println("Binary representation is = " + Integer.toBinaryString(i));
        System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(i));

        int j = -57; // negative number
        System.out.println("Original Number is " + j);
        System.out.println("Binary representation is = " + Integer.toBinaryString(j));
        System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(j));
    }
}

This code will print the original number, its binary representation, and the number of trailing zeros following the lowest-order one bit.

Compile and run the Java class

To compile the class, execute the following command in the terminal.

javac NumberOfTrailingZerosDemo.java

Running the compiled class can be done using the following command.

java NumberOfTrailingZerosDemo

The output of the program will be as follows.

Original Number is 170
Binary representation is = 10101010
Number of trailing zeros is 1
Original Number is -57
Binary representation is = 11111111111111111111111111000111
Number of trailing zeros is 0

User Input Example

Here's an example that allows a user to input a number and prints the number of trailing zeros.

Add the below code to the main() function:

try {
    System.out.println("Enter the number ");
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    System.out.println("Binary representation is = " + Integer.toBinaryString(i));
    System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(i));
} catch (Exception e) {
    System.out.println("Invalid input");
}

Compile and run the modified Java class

To compile the class, execute the following command in the terminal.

javac NumberOfTrailingZerosDemo.java

Running the compiled class can be done using the following command.

java NumberOfTrailingZerosDemo

The output of the program will be like:

Enter the number
87
Binary representation is = 1010111
Number of trailing zeros is 0

Test the Live Example

Now that you know how NumberOfTrailingZeros() method works, you can test out a live example to see if you can produce similar output.

import java.lang.*;

public class NumberOfTrailingZerosDemo {
    public static void main(String[] args) {
            int i = 500; //2 trailing zeros

            System.out.println("Number is like : "+ i);
            System.out.println("Binary representation is = " + Integer.toBinaryString(i));
            System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(i));

            int j = 456; //2 trailing zeros
            System.out.println("Number is like : "+ j);
            System.out.println("Binary representation is = " + Integer.toBinaryString(j));
            System.out.println("Number of trailing zeros is " + Integer.numberOfTrailingZeros(j));

            int k = -8; //3 leading zeros
            System.out.println("Number is like : "+ k);
            System.out.println("Binary representation is = " + Integer.toBinaryString(k));
            System.out.println("Number of zeros behind the rightmost 1-bit is " + Integer.numberOfTrailingZeros(k));
    }
}

Execute the above code in the terminal to get the output.

javac NumberOfTrailingZerosDemo.java
java NumberOfTrailingZerosDemo

which will produce the following output.

Number is like : 500
Binary representation is = 111110100
Number of trailing zeros is 2
Number is like : 456
Binary representation is = 111001000
Number of trailing zeros is 2
Number is like : -8
Binary representation is = 11111111111111111111111111111000
Number of zeros behind the rightmost 1-bit is 3

Save the code to GitHub

Now that you have successfully written code for NumberOfTrailingZeros() method, saved it to the ~/project/NumberOfTrailingZerosDemo.java directory, and run the code successfully, it is important to save it on GitHub for future reference. Use the following steps to push the code to the GitHub repository.

  1. Initialize the local directory as a Git repository.
git init
  1. Add the files in your new local repository. This stages them for the first commit.
git add .
  1. Commit the files that you've staged in your local repository.
git commit -m 'first commit'
  1. In the Command prompt, add the URL for the remote repository where your local repository will be pushed.
git remote add origin <REMOTE_URL>
## Example
## git remote add origin https://github.com/user/repo.git
  1. Push the changes in your local repository to GitHub.
git push origin master

Update the code on GitHub

To update the code on GitHub, follow the steps below.

  1. Add the new changes to the local repository.
git add .
  1. Commit the files that you've staged in your local repository.
git commit -m 'commit message'
  1. Push the changes in your local repository to GitHub.
git push origin branch-name

Retrieving the code from GitHub

To retrieve the code that you committed to the GitHub repository, use the following command.

git clone <git-repo-url>

Clean up the Local Environment

After completing your exercise, you should clean up your environment by deleting the .java file that you created and compiled.

rm ~/project/NumberOfTrailingZerosDemo.java
rm ~/project/NumberOfTrailingZerosDemo.class

Summary

In this lab, we learned how to use NumberOfTrailingZeros() method in Java. Also, covered examples with different input numbers and how output changes with different inputs. We also covered how to save the code on GitHub.

Other Java Tutorials you may like