Convert Octal to Decimal in Java
Problem
In an octal number each digit is worth a power of eight, so 517 in octal equals 5×64 + 1×8 + 7 = 335.
Given a string holding an octal number, print its decimal value, rejecting digits outside 0 to 7.
Java Program
public class OctalToDecimal {
public static void main(String[] args) {
String octal = "517";
int decimal = 0;
for (char digit : octal.toCharArray()) {
int value = digit - '0';
if (value < 0 || value > 7) {
System.out.println("Not a valid octal digit: " + digit);
return;
}
decimal = decimal * 8 + value; // each step moves the earlier digits up one power of 8
}
System.out.println("Decimal of " + octal + ": " + decimal);
}
}Output
Core Logic
Multiplying the running total by 8 before adding each digit places every earlier digit at the right power of eight.
- 1
digit - '0'converts each character to its numeric value. - 2Any value outside 0 to 7 is reported as invalid, and the program stops.
- 3
decimal * 8 + valueshifts the total one octal place and adds the new digit. - 4After the last digit,
decimalholds the full base-10 value.
517: 5 → 5×8 + 1 = 41 → 41×8 + 7 = 335.Key Point: Validating each digit matters — without it, an input like "519" would silently produce a wrong number instead of an error.
Why: Each of the n digits is checked and folded into one running total.
Key Concepts
Approach 2: Using Integer.parseInt() with Radix 8
public class OctalToDecimalBuiltIn {
public static void main(String[] args) {
String octal = "517";
System.out.println("Decimal of " + octal + ": " + Integer.parseInt(octal, 8));
try {
Integer.parseInt("519", 8); // 9 is not an octal digit
} catch (NumberFormatException e) {
System.out.println("519 is not valid octal");
}
}
}
Output
Core Logic
Passing 8 as the radix makes parseInt read the digits as octal and reject anything that isn't a valid octal digit.
- 1
Integer.parseInt("517", 8)returns335. - 2
Integer.parseInt("519", 8)throws aNumberFormatExceptionbecause 9 is not an octal digit. - 3The
catchblock turns that exception into a readable message.
335 and then the invalid-input message.Key Point: Beware of Java source literals: int x = 0517; is also octal (335), a classic trap when someone pads a number with a leading zero.
Why: The parser reads each character once.
Key Concepts
Interview Questions
How do you validate an octal string?
Every character must be between '0' and '7'; s.matches("[0-7]+") checks it in one call.
What is 777 octal in decimal?
511 (7 × 64 + 7 × 8 + 7).