Java Program to convert int to binary string

Java 8Object Oriented ProgrammingProgramming

The Integer.toBinaryString() method in Java converts int to binary string.

Let’s say the following are our integer values.

int val1 = 9;
int val2 = 20;
int val3 = 2;

Convert the above int values to binary string.

Integer.toBinaryString(val1);
Integer.toBinaryString(val2);
Integer.toBinaryString(val3);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      int val1 = 9;
      int val2 = 20;
      int val3 = 30;
      int val4 = 78;
      int val5 = 2;
      System.out.println("Converting integer "+val1+" to Binary String: "+Integer.toBinaryString(val1));
      System.out.println("Converting integer "+val2+" to Binary String: "+Integer.toBinaryString(val2));
      System.out.println("Converting integer "+val3+" to Binary String: "+Integer.toBinaryString(val3));
      System.out.println("Converting integer "+val4+" to Binary String: "+Integer.toBinaryString(val4));
      System.out.println("Converting integer "+val5+" to Binary String: "+Integer.toBinaryString(val5));
   }
}

Output

Converting integer 9 to Binary String: 1001
Converting integer 20 to Binary String: 10100
Converting integer 30 to Binary String: 11110
Converting integer 78 to Binary String: 1001110
Converting integer 2 to Binary String: 10
raja
Published on 13-Dec-2018 09:30:09
Advertisements