java.lang.Long.lowestOneBit() method with examples

Hello Friends, in this tutorial we look at an inbuilt method java.lang.Long.lowestOneBit() in Java. Here we talk about, what is the parameter, what it takes, what it returns and how to invoke it.

java.lang.Long.lowestOneBit() method

The computer understands integers in its binary form. So, java.lang.Long.lowestOneBit() is an inbuilt Java method which on passing an integer returns the value using its rightmost set bit only. In other words,  it finds the position(pos) of first ser bit in the number in its binary form and returns  2^(pos-1) as its output. It returns 0 if the number passed does not have any set bit in it.

If any other type such as string or decimal number is passed to this method it returns an error.

Let’s look at some examples:

  1. Input   = 10, in the binary form it is 1010, so first set bit is at 2nd position from the right, so it returns 2 as its output.
  2. Number = 8, in the binary form it is 1000, so first set bit is at 4th position from the right, so it returns 8 as its output.
  3. Number = 12, in the binary form it is 1100, so first set bit is at 3rd position from the right, so it returns 4 as its output.
  4. Number = 11, in the binary form it is 1011, so first set bit is at 1st position from the right, so it returns 1 as its output.
  5. Number = -12 in the binary form is 1111111111111111111111111111111111111111111111111111111111110100 so it returns 4 as output.

Implementation of this method in java:

import java.util.*;


class getlowestonebit{
  public static void main(String[] args) {
      
      int num1 = 10;
      int num2 = 8;
      int num3 = 12;
      int num4 = 11;
      int num5 = -12 ;  // 1111111111111111111111111111111111111111111111111111111111110100 
      

      System.out.println("Lowest one bit value of " + num1 + " is : "   + Long.lowestOneBit(num1));
      System.out.println("Lowest one bit value of " + num2 + " is : "   + Long.lowestOneBit(num2));
      System.out.println("Lowest one bit value of " + num3 + " is : "   + Long.lowestOneBit(num3));
      System.out.println("Lowest one bit value of " + num4 + " is : "   + Long.lowestOneBit(num4));
      System.out.println("Lowest one bit value of " + num5 + " is : "   + Long.lowestOneBit(num5));


  }
}

On compiling it with javac getlowestonebit.java and executing using java getlowestonebit we get the output as:

Lowest one bit value of 10 is : 2
Lowest one bit value of 8 is : 8
Lowest one bit value of 12 is : 4
Lowest one bit value of 11 is : 1
Lowest one bit value of -12 is : 4

Thank You

Leave a Reply