Integer highestOneBit() Method in Java
The Integer.highestOneBit() method of java.lang returns an integer value with at most a single one-bit which is in the position of the highest-order (ie.leftmost) one-bit for the given int value. If the specified value has no one-bits in its two’s complement binary representation then it returns zero, simply if it is equal to zero.
public static int highestOneBit(int a)
Parameters: The method takes one parameter a of integer type that refers to the value whose highest order bit is to be returned or on which the operation is to be performed.
Returns : The method can return two types of values:
- Returns an integer value with a single 1-bit, in the position of the highest-order one-bit in the specified value
- Returns zero if the specified value is equal to zero.
Input: 19 Output: Highest one bit of the given integer is = 16 Input: -9 Output: Highest one bit of the given integer is = -2147483648 Explanation: Consider any integer a = 19 Binary Representation = 0001 0011 Highest bit(at 4) i.e.0001 0000 so result = 2^4=16
Below programs illustrate the Java.lang.Integer.highestOneBit() Method.
Program 1: For a positive number.
Number is = 29 Highest one bit of the given integer is = 16 Number is = 44 Highest one bit of the given integer is = 32
Program 2: For a negative number.
Number is = -9 Highest one bit of the given integer is = -2147483648
Program 3: For a decimal value.
Note:It returns an error message when a decimal value is passed as an argument because of incompatible types.
prog.java:9: error: incompatible types: possible lossy conversion from double to int int a = 84.22; ^ 1 error
Program 4: For a String.
Note:It returns an error message when a String is passed as an argument because of incompatible types.
prog.java:9: error: incompatible types: String cannot be converted to int int a = "34"; ^ 1 error
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.