Program for Decimal to Binary Conversion in Java

Decimal to Binary Conversion

Converting a decimal number to binary involves representing the number in base-2, where each digit is either 0 or 1.

We will explore three methods to perform this conversion using Java programming.

Method 1: Using Built-in Function

We use Java's built-in Integer.toBinaryString() method.

public class DecimalToBinary {
    public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int num = scanner.nextInt();
        System.out.println("Binary: " + Integer.toBinaryString(num));
        scanner.close();
    }
}
            

Method 2: Using Division by 2

We repeatedly divide the number by 2 and store the remainder.

public class DecimalToBinaryManual {
    public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int num = scanner.nextInt();
        StringBuilder binary = new StringBuilder();
        while (num > 0) {
            binary.append(num % 2);
            num /= 2;
        }
        System.out.println("Binary: " + binary.reverse());
        scanner.close();
    }
}
            

Method 3: Using Recursion

We use recursion to keep dividing the number by 2 until it becomes 0, printing the remainder in reverse order.

public class DecimalToBinaryRecursive {
    public static void decimalToBinary(int n) {
        if (n == 0) return;
        decimalToBinary(n / 2);
        System.out.print(n % 2);
    }
    
    public static void main(String[] args) {
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        System.out.print("Enter a decimal number: ");
        int num = scanner.nextInt();
        if (num == 0) System.out.print("0");
        else decimalToBinary(num);
        System.out.println();
        scanner.close();
    }
}
            
Numbers

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

HCF - Highest Common Factor: C C++ Java Python

LCM - Lowest Common Multiple: C C++ Java Python

GCD - Greatest Common Divisor: C C++ Java Python

Binary to Decimal Conversion: C C++ Java Python

Octal to Decimal Conversion: C C++ Java Python

Hexadecimal to Decimal Conversion: C C++ Java Python

Decimal to Binary Conversion: C C++ Java Python

Decimal to Octal Conversion: C C++ Java Python

Decimal to Hexadecimal Conversion: C C++ Java Python

Binary to Octal Conversion: C C++ Java Python

Quadrants in which a given coordinate lies: C C++ Java Python

Addition of Two Fractions: C C++ Java Python

Calculate the Area of a Circle: C C++ Java Python

Convert Digit/Number to Words: C C++ Java Python

Finding Roots of a Quadratic Equation: C C++ Java Python