Convert Octal to Binary in Java

Topic: Convert Octal to Binary

In this program, we will convert an octal number (base 8) to its binary equivalent (base 2). Octal numbers only use digits from 0 to 7. Each digit of an octal number can be directly converted to a group of 3 binary digits. For example, octal digit 7 is 111 in binary. This is a great example for understanding number systems and conversions in Java.

Examples

Example 1:
Input: 7
Output: 111
Explanation: 7 in octal is 111 in binary.

Example 2:
Input: 10
Output: 1000
Explanation: Octal 1 is binary 001, and 0 is binary 000 → 001000 → after removing leading zeros → 1000.

Example 3 (Edge Case):
Input: 0
Output: 0
Explanation: Octal 0 is Binary 0.

Interviewer Expectations

Interviewers use this problem to test your understanding of:

  • Number system conversions (octal to binary)
  • String manipulation in Java
  • Basic control structures like loops
  • Input validation (handling invalid digits)

Approach

We will convert each digit of the octal number (read as a string) to its 3-bit binary equivalent using a lookup table or Java’s built-in conversion methods. This makes the solution simple and efficient.

Dry Run:

Octal Input: 25
Step-by-step:

  • 2 → binary 010
  • 5 → binary 101

Final Binary: 010101 → After removing leading 0s: 10101

Java Program

public class OctalToBinary {
    public static void main(String[] args) {
        String octal = "25";
        String binary = "";

        for (int i = 0; i < octal.length(); i++) {
            char digit = octal.charAt(i);
            int decimal = Character.getNumericValue(digit);
            String binPart = String.format("%3s", Integer.toBinaryString(decimal)).replace(' ', '0');
            binary += binPart;
        }

        binary = binary.replaceFirst("^0+(?!$)", ""); // Remove leading zeros
        System.out.println("Binary equivalent: " + binary);
    }
}
Binary equivalent: 10101

Possible Followup Questions with Answers

1. What happens if the input contains invalid digits like '8' or '9'?

Octal numbers only include digits from 0 to 7. You should validate the input using a condition like:

if (digit < '0' || digit > '7') {
    System.out.println("Invalid octal digit found!");
    return;
}

2. Can we convert octal to binary using decimal as an intermediate?

Yes, convert octal to decimal first, then convert decimal to binary using Integer.toBinaryString().

int decimal = Integer.parseInt(octal, 8);
String binary = Integer.toBinaryString(decimal);

3. How would you modify the program to accept user input?

Use the Scanner class:

Scanner sc = new Scanner(System.in);
System.out.print("Enter an octal number: ");
String octal = sc.nextLine();

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...