Java program to convert integer value into binary

Let’s learn java program to convert integer value into binary.

Java program to convert integer value into binary

To convert an integer to binary string in java first user enters an integer number as input using nextInt() method of Scanner class.

java program to convert integer value into binary

This number is stored in integer variable “num”. Then in while loop we check variable “num” is greater than 0.

Also read – how to convert decimal to binary in java using inbuilt function

If variable “num” is greater than zero then inside while loop using modulus and division operator given input is converted into binary.

Here’s how to convert int to binary in java.

import java.util.*;
import java.util.Scanner;
public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter the a number : ");
      num = sc.nextInt();
      // convert int to binary java
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}


Output:

Please enter the a number : 12
The binary conversion is : 1100


Also read – decimal to binary in java using while loop

Also read – java program to convert decimal to binary without using array


java integer to binary string with leading zeros

To get binary string with leading zeros use format() method of class String.

For example we have number

int a = 569;

Now we want to convert value 569 to String with length 6. Given value has only 3 digits. Desired string value is,

Also read – java program to convert decimal to binary using for loop

String str = “000569”;

String format() method returns a formatted string using the specified format string and arguments.

Syntax:

public static String format(String format, Object… args)

The locale always used is the one returned by Locale.getDefault().

String.format method can be used in JDK 1.5 or higher.

int a = 569;
String str = String.format("%06d", a);
System.out.println(str);  // 000569
String str = String.format("%010d", a);
System.out.println(str);  // 0000000569


Also read – java program to convert binary to decimal