Convert Decimal to Binary in Java

Topic

In this program, you'll learn how to convert a decimal number (base-10) to its binary (base-2) representation using Java. This is a common interview problem that helps assess a candidate’s understanding of loops, number systems, and string manipulation.

In binary, each digit represents a power of 2. The conversion involves dividing the decimal number by 2 repeatedly and recording the remainders.

Examples

Example 1:

Input: 5
Output: 101

Explanation: 5 / 2 = 2 remainder 1 → 2 / 2 = 1 remainder 0 → 1 / 2 = 0 remainder 1 → Binary: 101

Example 2:

Input: 8
Output: 1000

Explanation: 8 / 2 = 4 r 0 → 4 / 2 = 2 r 0 → 2 / 2 = 1 r 0 → 1 / 2 = 0 r 1 → Binary: 1000

Example 3 (Edge Case):

Input: 0
Output: 0

Explanation: Zero in decimal is also zero in binary.

Interviewer Expectations

The interviewer expects you to:

  • Understand number base conversion (decimal to binary).
  • Use loops and conditions appropriately.
  • Manipulate strings or use a stack-like structure.
  • Handle edge cases like 0 or negative input gracefully.

Approach

We use a while loop to repeatedly divide the number by 2 and store the remainders. Each remainder forms the binary digits from right to left, so we build the binary string in reverse order.

Dry Run

Let’s dry run for input 10:

  • 10 / 2 = 5 remainder 0
  • 5 / 2 = 2 remainder 1
  • 2 / 2 = 1 remainder 0
  • 1 / 2 = 0 remainder 1

Binary = 1010 (reverse of collected remainders)

Java Program

public class DecimalToBinary {
    public static void main(String[] args) {
        int decimal = 10;
        String binary = "";
        int temp = decimal;
        while (temp > 0) {
            int remainder = temp % 2;
            binary = remainder + binary;
            temp = temp / 2;
        }
        System.out.println("Binary of " + decimal + " = " + (binary.isEmpty() ? "0" : binary));
    }
}
Binary of 10 = 1010

Possible Followup Questions with Answers

Q1: How do you convert binary back to decimal in Java?

Use Integer.parseInt(binaryStr, 2). Example:

int decimal = Integer.parseInt("1010", 2); // returns 10

Q2: Can you write a recursive version of this program?

public static String toBinary(int n) {
    if (n == 0) return "";
    return toBinary(n / 2) + (n % 2);
}

Q3: How do you handle negative numbers?

One way is to use the Integer.toBinaryString() method which gives two's complement representation:

System.out.println(Integer.toBinaryString(-10));

Q4: Can you use built-in Java methods to do the conversion?

String binary = Integer.toBinaryString(10);

This is allowed in interviews only if the focus is not on algorithm logic.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...