Java Long LowestOneBit Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the lowestOneBit() method of the Long class in Java. This method returns the single one-bit long value of long passed as an argument in the position of the lowest order(rightmost) and returns zero if the passed argument is zero.

Create a Java file

Create a file named LowestOneBit.java in the ~/project directory by running the following command in the terminal:

touch ~/project/LowestOneBit.java

Write the Java code

Open the LowestOneBit.java file in a text editor and paste the below code in it:

import java.util.Scanner;

public class LowestOneBit {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        try {
            System.out.print("Enter a long integer: ");
            long input = sc.nextLong();

            // Get the lowest one-bit value
            long lowestOneBit = Long.lowestOneBit(input);

            if (input != 0) {
                System.out.println("The lowest one-bit value of " + input + " is " + lowestOneBit);
            } else {
                System.out.println("The value of 0 does not have a lowest one-bit.");
            }
        } catch (Exception e) {
            System.out.println("Invalid input. Please enter a long integer.");
        } finally {
            sc.close();
        }
    }
}

Compile and run the code

Compile the LowestOneBit.java file by running the following command:

javac LowestOneBit.java

Run the compiled file by running the following command:

java LowestOneBit

Test the program

When you run the program, the following output is displayed:

Enter a long integer: 95232
The lowest one-bit value of 95232 is 1024

Enter any long integer of your choice and the program will output the lowest one-bit value of the input.

Enter a long integer: -15
The lowest one-bit value of -15 is 1

If the input is 0, the program will output that the value of 0 does not have a lowest one-bit.

Enter a long integer: 0
The value of 0 does not have a lowest one-bit.

Summary

In this lab, you learned how to use the lowestOneBit() method of the Long class in Java to get the single one-bit long value of long passed as an argument in the position of the lowest order(rightmost) and returns zero if the passed argument is zero. You first created a Java file and wrote the code to implement the lowestOneBit() method. You compiled and ran the code to test the program and verified the output by entering different long integers.

Other Java Tutorials you may like