Java Program to Convert Integer to Binary

Learn a java program to convert Integer to Binary using modulo and division operations and the Integer.toBinaryString() method with examples.

In Java, there are multiple ways to convert an integer into its binary representation. A binary number consists of only 0s and 1s.

In this example, we will learn how to convert an integer to binary in Java using two approaches:

  1. Using the modulo (%) and division (/) operators
  2. Using the Integer.toBinaryString() method

Using Modulo and For Loop Method

  • A binary number consists of only 0s and 1s.
  • First, create an integer array to store the binary digits.
  • Calculate the remainder using the modulo operator (% 2) and store the remainder in the array.
  • Divide the number by 2 after each iteration.
  • Repeat the process until the Number becomes 0.
  • The remainders are stored in reverse order in the binary array.
  • Use a for loop to iterate through the array in reverse order.
  • Print each element to get the binary representation of the integer.

Using toBinaryString() Method

  • Java provides the Integer.toBinaryString() method to convert an integer into its binary string representation.
  • This method accepts an int value as an argument.
  • It returns the binary representation of the integer as a String.
				
					public class ConvertDecimalToBinary {

    // Using modulo and for loop method
    public void printBinaryData(int number) {

        System.out.println("Using Modulo and for loop method:");

        int[] binary = new int[32];
        int index = 0;

        while (number > 0) {
            binary[index++] = number % 2;
            number = number / 2;
        }

        for (int i = index - 1; i >= 0; i--) {
            System.out.print(binary[i]);
        }

        System.out.println();
    }

    public static void main(String[] args) {

        ConvertDecimalToBinary cdtb = new ConvertDecimalToBinary();

        int value = 57;

        cdtb.printBinaryData(value);

        // Using toBinaryString() method
        System.out.println("Using toBinaryString() method: "
                + Integer.toBinaryString(value));
    }
}
				
			

Output :-
Using Modulo and for loop method:
111001
Using toBinaryString() method: 111001

Java Program Using Modulo Without an Array

				
					public class ConvertIntegerToBinary {

    public static void main(String[] args) {

        int number = 57;
        String binary = "";

        while (number > 0) {
            int remainder = number % 2;
            binary = remainder + binary;
            number = number / 2;
        }

        System.out.println("Binary value: " + binary);
    }
}
				
			

Output :-
Binary value: 111001