How To Convert Decimal To Binary In Java

Binary numbers are extremely important in the realm of computer programming. In conclusion, every bit of data in a computer is represented as a binary string of 0s and 1s. Programmers must therefore understand how to translate decimal numbers towards binary numbers. One of the most extensively used programming languages in the world, Java, offers a variety of possibilities for performing this conversion.

In this blog post, we will examine one of the simplest techniques for converting decimal integers to binary numbers in Java.

By the end of this blog post, readers will have a solid understanding of how to convert decimal to binary in Java, which is an essential skill for any programmer working with binary data.

Whether you are just starting to learn Java programming or you are an experienced programmer looking to refresh your knowledge, this blog post will provide valuable insights and practical tips for converting decimal numbers to binary numbers in Java.

Why it is important to convert decimal to binary

Computers process and store data in binary form, so any data that needs to be handled by a computer must be transformed into binary format. Binary is the language of computers.

1. Efficiency: For arithmetic and logical operations, binary numbers are more effective than decimal numbers. Binary number conversion can improve code efficiency and decrease memory usage.

2. Data compression is more appropriate with binary data than with decimal data. Data transfer rates can be increased and file sizes can be minimized by converting decimal data to binary.

3. Network communication: Binary format is extensively used for data transfer via networks. To ensure that data is accurately transmitted and received by various devices and platforms, decimal information has to be transformed to binary.

4. Cryptography: Keys, passwords, and other private information are frequently represented by binary integers in cryptography. Sensitive information must be encapsulated and decrypted using binary conversion of decimal data.

Different approaches to convert decimal to binary

Following are the methods which answer the question how to convert decimal to binary in Java.

1. Divide-by-2 algorithm

2. Bitwise shift operator

3. Integer.toBinaryString() method

4. StringBuilder

5. Recursive algorithm

Detailed Explanation:

1. Divide-by-2 algorithm:

The divide-by-2 algorithm is a common method used to convert decimal numbers to binary numbers. This algorithm involves dividing the decimal number by 2 and keeping track of the remainder, which corresponds to a binary digit. The process is repeated until the quotient becomes 0.

In Java, this algorithm can be implemented using a loop and string concatenation.

Sample Code:

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt();

        String binary = ""; // initialize an empty string to hold the binary digits

        while (decimal > 0) {
            int remainder = decimal % 2; // get the remainder of dividing the decimal by 2
            binary = remainder + binary; // prepend the remainder to the binary string
            decimal = decimal / 2; // divide the decimal by 2
        }

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

}

Output:

Enter a decimal number: 23
Binary equivalent: 10111

Code explanation:

  1. Import the java.util.Scanner class to read user input.
  2. Define a main method that creates a Scanner object to read user input and prompts the user to enter a decimal number.
  3. Read the decimal number entered by the user using the nextInt method of the Scanner class.
  4. Initialize an empty string called binary to hold the binary digits.
  5. Implement the divide-by-2 algorithm using a while loop that continues until the decimal number becomes 0. Inside the loop:
  6. Get the remainder of dividing the decimal number by 2 using the % operator.
  7. Prepend the remainder to the binary string using string concatenation.
  8. Divide the decimal number by 2 using integer division (/).
  9. Print the binary equivalent of the decimal number using the println method of the System.out object.

2. Bitwise shift operator:

In Java, we can also use the bitwise shift operator to convert decimal to binary. The binary representation of a decimal number can be obtained by shifting the bits of the number to the right, effectively dividing it by 2.

The remainder can be obtained using the bitwise AND operator (&). This process is repeated until the number becomes 0.

Sample Code:

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt();

        String binary = ""; // initialize an empty string to hold the binary digits

        while (decimal > 0) {
            int bit = decimal & 1; // get the least significant bit of the decimal number
            binary = bit + binary; // prepend the bit to the binary string
            decimal = decimal >>> 1; // shift the bits of the decimal number to the right
        }

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

}

Output:

Enter a decimal number: 23
Binary equivalent: 10111

Code explanation:

  1. Import the java.util.Scanner class to read user input.
  2. Define a main method that creates a Scanner object to read user input and prompts the user to enter a decimal number.
  3. Read the decimal number entered by the user using the nextInt method of the Scanner class.
  4. Initialize an empty string called binary to hold the binary digits.
  5. Implement the bitwise shift operator using a while loop that continues until the decimal number becomes 0. Inside the loop:
  6. Get the least significant bit of the decimal number using the bitwise AND operator (&) with 1.
  7. Prepend the bit to the binary string using string concatenation.
  8. Shift the bits of the decimal number to the right using the bitwise shift operator (>>>).
  9. Print the binary equivalent of the decimal number using the println method of the System.out object.

3. Integer.toBinaryString() method:

In Java, we can also use the Integer.toBinaryString() method to convert a decimal number to its binary equivalent. This method converts the decimal number to a binary string representation.

Sample code:

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt(); // read decimal input from user

        String binary = Integer.toBinaryString(decimal); // convert decimal to binary using toBinaryString()

        System.out.println("Binary equivalent: " + binary); // print binary equivalent
    }

}

Output:

Enter a decimal number: 23
Binary equivalent: 10111

Code explanation:

  1. Import the java.util.Scanner class to read user input.
  2. Define a main method that creates a Scanner object to read user input and prompts the user to enter a decimal number.
  3. Read the decimal number entered by the user using the nextInt method of the Scanner class.
  4. Use the Integer.toBinaryString() method to convert the decimal number to its binary equivalent and store the result in a string called binary.
  5. Print the binary equivalent of the decimal number using the println method of the System.out object.

4. StringBuilder:

This method provides an alternative way to convert a decimal number to binary using a StringBuilder. The StringBuilder allows for efficient appending of the binary digits and can be reversed at the end to produce the correct order.

Sample Code:

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt();
        
        StringBuilder binary = new StringBuilder(); // create an empty StringBuilder

        while (decimal > 0) {
            binary.append(decimal % 2); // append the remainder to the StringBuilder
            decimal /= 2; // divide decimal by 2
        }

        String binaryString = binary.reverse().toString(); // reverse the StringBuilder and convert to a String

        System.out.println("Binary equivalent: " + binaryString);
    }

}

Output:

Enter a decimal number: 42
Binary equivalent: 101010

Code explanation:

  1. The Scanner class is imported to read user input.
  2. The main method creates a Scanner object and prompts the user to enter a decimal number.
  3. The decimal number entered by the user is read using the nextInt method of the Scanner class and stored in an integer variable called decimal.
  4. A StringBuilder object called binary is created to hold the binary digits.
  5. A while loop is used to convert the decimal number to binary. The loop continues as long as the decimal is greater than zero.
  6. In each iteration of the loop, the remainder of the decimal divided by 2 is appended to the binary StringBuilder using the append method.
  7. The decimal variable is divided by 2 to shift the bits to the right.
  8. Once the loop completes, the binary StringBuilder is reversed using the reverse method and converted to a string using the toString method.
  9. The binary equivalent is stored in a string variable called binaryString.
  10. The binary equivalent is printed to the console using the println method of the System.out object.

5. Recursive algorithm:

Another way to convert a decimal number to binary in Java is by using a recursive algorithm. This method involves dividing the decimal number by 2 and storing the remainder. The quotient is then used as input to a recursive call until the quotient is zero.

The binary representation is then formed by concatenating the remainder from the recursive calls in reverse order.

Sample code:

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt();

        String binary = decimalToBinary(decimal); // call the recursive method

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

    // Recursive method to convert decimal to binary
    public static String decimalToBinary(int decimal) {
        if (decimal == 0) {
            return "0"; // base case: return "0" when decimal is zero
        } else if (decimal == 1) {
            return "1"; // base case: return "1" when decimal is one
        } else {
            // recursive case: call the method with quotient and append remainder
            return decimalToBinary(decimal / 2) + Integer.toString(decimal % 2);
        }
    }
}

Output:

Enter a decimal number: 42
Binary equivalent: 101010

Code explanation:

  1. Take the decimal input from the user using a Scanner.
  2. Call the decimalToBinary method with the decimal input as an argument.
  3. In the decimalToBinary method:
  4. If the decimal input is zero, return “0” (base case).
  5. If the decimal input is one, return “1” (base case).
  6. If the decimal input is greater than one:
  7. Call the decimalToBinary method with the quotient of the division of the decimal by 2 as argument (recursive case).
  8. Append the remainder of the division of the decimal by 2 to the result of the recursive call.
  9. Return the final result.
  10. Print the binary equivalent of the decimal input to the console.

Best approach out of five

Integer.toBinaryString() is considered the best method when it comes to solve the question how to convert decimal to binary in Java for the following reasons:

  1. Simplicity: The Integer.toBinaryString() method is a built-in method in Java, which means that it does not require any additional implementation or setup. It takes an integer input and returns its binary representation as a string, making it a simple and straightforward solution.
  2. Efficiency: The toBinaryString() method internally uses a bitwise shift and OR operation to convert the decimal number to binary. These operations are optimized for performance and make the toBinaryString() method more efficient than other approaches.
  3. Error handling: The toBinaryString() method handles edge cases such as negative input values and large integers. It throws an exception for negative input values and returns the two’s complement of the absolute value. It also handles large integers by returning a binary string with the appropriate number of digits.
  4. Flexibility: The toBinaryString() method can be used in various Java applications, including web applications, desktop applications, and mobile applications. It can be used to convert decimal to binary for mathematical computations, data storage, and data transmission.

Overall, the Integer.toBinaryString() method is the best method to convert decimal to binary in Java because it is simple, efficient, handles edge cases, and can be used in various Java applications.

Sample Problems

These are some problems to solve how to convert from decimal to binary in java

Sample Problem 1:

Write a Java program that prompts the user to input a decimal number, and then displays its binary equivalent using divide by 2 algorithm.

Solution:

  1. Ask the user to input a decimal number.
  2. Read the user’s input as an integer.
  3. Initialise an empty string to store the binary digits.
  4. Divide the decimal number by 2 and keep track of the remainder.
  5. Add the remainder to the beginning of the binary string.
  6. If the decimal number is now zero, stop.
  7. Otherwise, update the decimal number to be the quotient of the previous division (i.e., decimal /= 2) and repeat from step 4.
  8. Once the decimal number is zero, return the binary string.

Code:

import java.util.Scanner;

public class DecimalToBinary {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create a Scanner object to read user input
        System.out.print("Enter a decimal number: "); // Prompt the user to enter a decimal number
        int decimal = scanner.nextInt(); // Read the user's input as an integer
        String binary = decimalToBinary(decimal); // Convert the decimal number to binary using the decimalToBinary method
        System.out.println("Binary equivalent: " + binary); // Print the binary equivalent of the decimal number
    }
    
    public static String decimalToBinary(int decimal) {
        String binary = ""; // Initialize an empty string to store the binary digits
        while (decimal > 0) { // Continue until the decimal number is zero
            int remainder = decimal % 2; // Compute the remainder when the decimal number is divided by 2
            binary = remainder + binary; // Add the binary digit (0 or 1) to the beginning of the binary string
            decimal /= 2; // Divide the decimal number by 2 to prepare for the next iteration
        }
        return binary; // Return the binary string
    }
}

Output:

Enter a decimal number: 25
Binary equivalent: 11001

Sample Problem 2:

Write a Java program that converts a decimal number to its binary equivalent and then counts the number of 1’s in the binary representation using a bitwise shift operator.

Solution:

  1. Prompt the user to enter a decimal number.
  2. Read the decimal number as an integer.
  3. Convert the decimal number to its binary equivalent.
  4. Initialise a count variable to zero.
  5. Use a for loop to iterate over each binary digit.
  6. For each binary digit, use the bitwise AND operator to check whether the least significant bit is 1.
  7. If it is, increment the count variable.
  8. Display the binary equivalent of the decimal number and the number of 1’s in the binary representation.

Code:

import java.util.Scanner;

public class DecimalToBinaryAndCountOnes {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = scanner.nextInt();

        // Convert decimal to binary using divide by 2 algorithm
        String binary = "";
        while (decimal > 0) {
            int remainder = decimal % 2;
            binary = remainder + binary;
            decimal /= 2;
        }

        // Count the number of 1's in the binary representation using bitwise shift operator
        int count = 0;
        for (int i = 0; i < binary.length(); i++) {
            if ((Integer.parseInt(String.valueOf(binary.charAt(i))) & 1) == 1) {
                count++;
            }
        }

        // Display the binary equivalent and number of 1's in the binary representation
        System.out.println("Binary equivalent: " + binary);
        System.out.println("Number of 1's in binary representation: " + count);
    }
}

Output:

Enter a decimal number: 65
Binary equivalent: 1000001
Number of 1's in binary representation: 2

Sample Problem 3:

Write a Java program that takes an array of decimal numbers as input, and then converts each number to its binary equivalent using Integer.toBinaryString() method.

Solution:

  1. Import the java.util.Scanner class to read input from the user.
  2. Declare an integer array to store the decimal numbers entered by the user.
  3. Use the Scanner class to read the size of the array from the user.
  4. Initialize the integer array with the size entered by the user.
  5. Use a loop to read each decimal number from the user and store it in the array.
  6. Use another loop to iterate through the array and convert each decimal number to its binary equivalent using the Integer.toBinaryString() method.
  7. Print out the binary equivalent of each decimal number to the console.

Code:

import java.util.Scanner;

public class DecimalToBinaryArray {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the number of elements in the array
        System.out.print("Enter the number of elements: ");
        int n = scanner.nextInt();

        // Create an array to store the decimal numbers
        int[] decimalArray = new int[n];

        // Prompt the user to enter the decimal numbers
        for (int i = 0; i < n; i++) {
            System.out.print("Enter decimal number " + (i + 1) + ": ");
            decimalArray[i] = scanner.nextInt();
        }

        // Convert each decimal number to its binary equivalent using Integer.toBinaryString() method
        String[] binaryArray = new String[n];
        for (int i = 0; i < n; i++) {
            binaryArray[i] = Integer.toBinaryString(decimalArray[i]);
        }

        // Display the binary equivalents
        System.out.println("Binary equivalents:");
        for (int i = 0; i < n; i++) {
            System.out.println(decimalArray[i] + " -> " + binaryArray[i]);
        }
    }
}

Output:

Enter the number of elements: 5
Enter decimal number 1: 89
Enter decimal number 2: 45
Enter decimal number 3: 78
Enter decimal number 4: 63
Enter decimal number 5: 21
Binary equivalents:
89 -> 1011001
45 -> 101101
78 -> 1001110
63 -> 111111
21 -> 10101

Sample Problem 4:

Write a Java program that converts a decimal number to its binary equivalent using StringBuilder instead of the divide by 2 algorithm.

Solution:

  1. Import the java.util.Scanner class to read input from the user.
  2. Define a class named DecimalToBinaryStringBuilder.
  3. Define the main method.
  4. Create a Scanner object to read input from the user.
  5. Prompt the user to enter a decimal number and read the input using the nextInt method of the Scanner object.
  6. Create a StringBuilder object named binary to store the binary equivalent of the decimal number.
  7. Use a while loop to convert the decimal number to its binary equivalent:
  8. a. Calculate the remainder when the decimal number is divided by 2.
  9. b. Insert the remainder at the beginning of the StringBuilder object using the insert method.
  10. c. Divide the decimal number by 2.
  11. d. Repeat steps a-c until the decimal number becomes 0.
  12. Print the binary equivalent of the decimal number using the println method of the System.out object.

Code:

import java.util.Scanner;

public class DecimalToBinaryStringBuilder {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int decimal = scanner.nextInt();

        // Create a StringBuilder object to store the binary equivalent
        StringBuilder binary = new StringBuilder();

        // Convert decimal to binary
        while (decimal > 0) {
            int remainder = decimal % 2;
            binary.insert(0, remainder);
            decimal /= 2;
        }

        // Print the binary equivalent
        System.out.println("Binary equivalent: " + binary);
    }
}

Output:

Enter a decimal number: 569
Binary equivalent: 1000111001

Sample Problem 5:

Write a Java program that accepts an integer input from the user and converts it to its binary representation using the recursive algorithm.

Solution:

  1. We first import the Scanner class to accept input from the user.
  2. We then prompt the user to enter a decimal number.
  3. We call the decimalToBinary method and pass in the decimal number as a parameter.
  4. The decimalToBinary method checks if the decimal number is 0 or 1, and returns “0” or “1” respectively.
  5. If the decimal number is greater than 1, the method recursively calls itself with the integer division of the decimal number by 2 as the parameter, and concatenates the modulus of the decimal number by 2 to the result.
  6. Finally, the main method prints the binary equivalent of the decimal number to the console.

Code:

import java.util.Scanner;

public class DecimalToBinaryRecursive {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // create a Scanner object to read user input
        System.out.print("Enter a decimal number: ");
        int decimal = input.nextInt(); // read the decimal number from user input
        String binary = decimalToBinary(decimal); // call the decimalToBinary method to convert decimal to binary
        System.out.printf("Binary equivalent of %d  is %s\n", decimal, binary); // print the binary equivalent to the console
    }
    
    public static String decimalToBinary(int decimal) {
        if (decimal == 0) { // if decimal is 0, return "0"
            return "0";
        } else if (decimal == 1) { // if decimal is 1, return "1"
            return "1";
        } else { // for all other cases (when decimal > 1)
            // recursively call the decimalToBinary method with the integer division of decimal by 2,
            // and concatenate the modulus of decimal by 2 to the result
            return decimalToBinary(decimal / 2) + decimal % 2;
        }
    }
}

Output:

Enter a decimal number: 49
Binary equivalent of 49  is 110001

Conclusion

In conclusion, Java has various methods for converting decimal to binary, which is a fundamental operation in computer programming. Iteration and recursion are the two most typical approaches. The recursive method offers a more beautiful and succinct answer, but the iteration method is simple and uses elementary arithmetic operations.

Anybody learning Java programming should be familiar with these methods because they can be used for a variety of programming tasks, including bitwise operations and data representation.

Anyone can easily convert decimal integers to binary in Java by applying the steps provided in this blog. By the end of this blog, we learnt how to convert from decimal to binary in java.