Convert Octal to Decimal in Java

Topic

In this program, we will convert an octal number (base-8) into its decimal equivalent (base-10) using Java.

Octal numbers use digits from 0 to 7. Each digit's position represents a power of 8. For example, 745 (octal) means 7×8² + 4×8¹ + 5×8⁰ = 485 (decimal).

We will read the octal number as a string and process each digit to calculate the decimal value.

Examples

  • Input: 10
    Output: 8
    Explanation: 1×8¹ + 0×8⁰ = 8
  • Input: 17
    Output: 15
    Explanation: 1×8¹ + 7×8⁰ = 15
  • Input: 0
    Output: 0
    Explanation: 0×8⁰ = 0
  • Input: 123
    Output: 83
    Explanation: 1×8² + 2×8¹ + 3×8⁰ = 83

Interviewer Expectations

The interviewer is testing your understanding of:

  • Number system conversions (especially base-8 to base-10)
  • String and loop usage in Java
  • Mathematical logic and power calculations

Approach

Here's a beginner-friendly plan to convert an octal number to decimal:

  1. Read the octal number as a string.
  2. Initialize a variable to store the decimal result.
  3. Loop through each digit from right to left.
  4. Multiply the digit by 8 raised to its position and add to the result.

Dry Run

Let's dry run the input “123”:

Octal: 123 (from right to left)
3 × 8⁰ = 3
2 × 8¹ = 16
1 × 8² = 64
Total = 3 + 16 + 64 = 83

Java Program

public class OctalToDecimal {
  public static void main(String[] args) {
    String octal = "123";
    int decimal = 0;
    int power = 0;

    for (int i = octal.length() - 1; i >= 0; i--) {
      int digit = Character.getNumericValue(octal.charAt(i));
      decimal += digit * Math.pow(8, power);
      power++;
    }

    System.out.println("Decimal equivalent: " + decimal);
  }
}
Decimal equivalent: 83

Possible Followup Questions with Answers

Q1. What if the input contains a digit not allowed in octal (like 8 or 9)?

Answer: You should validate the input. If any digit is greater than 7, show an error message.

if (digit > 7) {
  System.out.println("Invalid octal digit: " + digit);
  return;
}

Q2. How would you handle user input from the console?

Answer: You can use the Scanner class to take input:

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

Q3. Can you write a program to convert decimal to octal?

Answer: Yes, use repeated division by 8 and store remainders:

int decimal = 83;
StringBuilder octal = new StringBuilder();

while (decimal > 0) {
  int rem = decimal % 8;
  octal.insert(0, rem);
  decimal /= 8;
}
System.out.println("Octal: " + octal);

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