Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java Long highestOneBit() Method

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

For example, the input of long 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 long highestOneBit(long i)

Parameters:

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

Returns:

Returns the single one-bit long 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 the highest bit is taken accordingly.

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


highest-order one-bit Long is: 16
highest-order one-bit Long is: -9223372036854775808

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);  
            Long i = sc.nextLong();  
            System.out.println("Highest-order one-bit Long is: "+Long.highestOneBit(i));  
        }
        catch(Exception e)
        {
            System.out.println("Exception occurred:" + e);  
        }
     }
}


Enter the number : 55
Highest-order one-bit Long is: 32
******************************************
Enter the number : -343
Highest-order one-bit Long is: -9223372036854775808

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.