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

Java program to convert integer value into binary

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

Then using modulus and division operator given input is converted into binary. Here’s how to convert int to binary in java,

// int to binary java
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();
      // 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


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).

// integer to binary java
import java.util.*;

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



Output:

tobinarystring : 10111