Java program to convert integer value into binary

Today we are going to learn java program to convert integer value into binary.

java program to convert integer value into binary

To print an integer in binary format in java first user enters an integer number as input.

Then using modulus and division operator given input is converted into binary.

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.print("Please enter the a number : ");
      num = sc.nextInt();
      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


Here we are going to learn binary conversion java using java lang.Integer.toBinaryString() method.

Also read – HashSet in java

This method returns the string representation of the unsigned integer value represented by the argument in binary (base 2).

import java.util.*;

public class IntToBinaryDemo
{
   public static void main(String[] args)
   {
      Integer num = new Integer(23);
      String strBinary = Integer.toBinaryString(num);
      System.out.println("Binary conversion : " + strBinary);
   }
}

Output:

Binary conversion : 10111