This post will discuss how to convert a number to binary in Java.

1. Using Built-in methods

The standard solution to convert a number to binary in Java is to use the Integer.toBinaryString() method, which returns the binary representation of the specified integer in string format.

Download  Run Code

Output:

1001011

 
Similarly, you can convert a long using the Long.toBinaryString() method.

Download  Run Code

Output:

1001011

 
Alternatively, you can use the toString(i, r) method, which returns the string representation i in the radix r. However, this doesn’t work as intended for negative numbers.

Download  Run Code

Output:

1001011

 
If you need binary representation of the integer to be left-padded with zeros, you can use any of the methods discussed in this post:

2. Naive Solution

We can even write a custom routine to convert a number in binary format, as shown below:

Download  Run Code

Output:

00000000000000000000000001001011

 
Here’s a recursive version of the above code:

Download  Run Code

Output:

00000000000000000000000001001011

That’s all about converting a number to binary in Java.