Signup/Sign In
LAST UPDATED: AUGUST 27, 2020

Java Integer highestOneBit() Method

Java highestOneBit() method is a part of the Integer class of the java.lang package. This method is used to return the single one-bit value of integer passed as argument in the position of the highest order(leftmost) and returns zero if the passed argument is zero.

For example, the input of int 17 will return 16; As 17 can be represented in binary as 10001 so it will return the furthest bit left which is equal to 16.

Syntax:

public static int highestOneBit(int n)

Parameters:

The parameter passed is the integer value whose highest order bit is to be returned.

Returns:

Returns the single one-bit integer value in the position of the highest order and zero if the parameter passed is zero.

Example 1:

Here, the binary equivalent of 20 is 10100, hence the highest order one bit is 16 and in case of negative binary the equivalent two's complement will be considered and highest bit is taken accordingly.

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        int i=20;
        int j=-12;
        
        System.out.println(" highest-order one-bit Integer is: "+Integer.highestOneBit(i));  
        System.out.println(" highest-order one-bit Integer is: "+Integer.highestOneBit(j));  
    }  
}


highest-order one-bit Integer is: 16
highest-order one-bit Integer is: -2147483648

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  
public class StudyTonight
{  
    public static void main(String[] args)
    {  
        try
        {
           System.out.print("Enter the number : ");  
           Scanner sc = new Scanner(System.in);  
           Integer i = sc.nextInt();  
           System.out.println("Highest-order one-bit Integer is: "+Integer.highestOneBit(i));  
        }
        catch(Exception e)
        {
          
        }
    }
}  


Enter the number : 90
Highest-order one-bit Integer is: 64
*****************************************
Enter the number : -54
Highest-order one-bit Integer is: -2147483648

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.