This post will discuss how to convert an integer to a binary string of a specific length in Java. The solution should left-pad the binary string with leading zeros.

There are several ways to convert an integer to binary format in Java:

1. Using String.format() method

To get a binary string of a specific length with leading zeros, we can use the format() method of the String class as follows:

Download  Run Code

Output:

0000001111101000

2. Custom routine

We can also write our own routine to convert an integer to a binary string of a specific length with leading zeros. This can be done using either a StringBuilder or a char array.

⮚ Using StringBuilder:

Download  Run Code

Output:

0000001111101000

⮚ Using char array:

Download  Run Code

Output:

0000001111101000

That’s all about converting an integer to a binary string of a specific length in Java.