Decimal to Binary Conversion in Java — Definition, Examples and Program

Learn how to convert a decimal number to binary in Java with clear explanation, step-by-step examples, and an easy-to-understand program.

Decimal to Binary Conversion in Java — Definition, Examples and Program

Binary numbers are numbers represented in base 2, using only 0s and 1s. Converting a decimal number (base 10) to binary (base 2) is a common operation in programming and computer science.

How to Convert Decimal to Binary?

  1. Divide the decimal number by 2.
  2. Write down the remainder.
  3. Update the number as the quotient from the division.
  4. Repeat steps 1–3 until the quotient becomes 0.
  5. The binary representation is the remainders read in reverse order.

Example 1

Decimal Number: 13

Binary: 1101

Example 2

Decimal Number: 25

Binary: 11001

Java Program for Decimal to Binary Conversion


import java.util.Scanner;

public class DecimalToBinary {

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

        System.out.print("Enter a decimal number: ");
        int decimal = sc.nextInt();

        int num = decimal;
        String binary = "";

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

        System.out.println("Binary of " + decimal + " is " + binary);
    }
}

Sample Output


Enter a decimal number: 13
Binary of 13 is 1101

Enter a decimal number: 25
Binary of 25 is 11001

Practice Challenges

  1. Write a program to convert decimal to binary without using strings (using array or bitwise operations).
  2. Modify the program to convert multiple decimal numbers entered by the user into binary.
  3. Write a program to convert decimal to octal and hexadecimal using similar logic.

Decimal to binary conversion is fundamental in computer science, digital electronics, and low-level programming. This Java program helps beginners understand the process step by step.