Java Integer.toBinaryString() – Examples
In this tutorial, we will learn about Java Integer.toBinaryString() method, and learn how to use this method to get the binary representation of given integer, with the help of examples.
toBinaryString(int i)
Integer.toBinaryString() returns a string value with the binary representation of the integer argument as an unsigned integer in base 2.
Syntax
The syntax of toBinaryString() method with an integer as parameter is
Integer.toBinaryString(int i)
where
Parameter | Description |
---|---|
i | The integer whose binary representation has to be found. |
Returns
The method returns value of type String.
Example 1 – toBinaryString()
In this example, we will take an integer, and find its binary representation using Integer.toBinaryString() method.
Java Program
public class Example {
public static void main(String[] args){
int i = 49;
String result = Integer.toBinaryString(i);
System.out.println("Result of toBinaryString("+i+") = " + result);
}
}
Output
Result of toBinaryString(49) = 110001
Example 2 – toBinaryString() – Negative Integer
In this example, we will take a negative integer, and find its binary representation using Integer.toBinaryString() method.
Since, given argument is negative, and the argument is considered as unsigned integer in base 2, we get 2’s complement of the given number.
Java Program
public class Example {
public static void main(String[] args){
int i = -49;
String result = Integer.toBinaryString(i);
System.out.println("Result of toBinaryString("+i+") = " + result);
}
}
Output
Result of toBinaryString(-49) = 11111111111111111111111111001111
Conclusion
In this Java Tutorial, we have learnt the syntax of Java Integer.toBinaryString() method, and also how to use this method with the help of Java example programs.