We can convert Octal to Decimal in Java in the following ways:
- Using the parseInt() method
- Using custom logic
Convert Octal to Decimal in Java using the parseInt() method
Integer class has a method parseInt(String s, int radix) that parses the String argument as a signed integer in the radix specified by the second argument.
Example
class Test { public static void main(String[] args) { String octalString = "142"; int decimalNumber = Integer.parseInt(octalString, 8); System.out.println(decimalNumber); } }
Output: 98
Parse Octal to Decimal using custom logic
There is always a way without using predefined methods, and that is with custom logic, like in the following example:
class Test { public static void main(String[] args) { int decimal = getDecimalFromOctal(125); System.out.println(decimal); } public static int getDecimalFromOctal(int octal) { int decimal = 0; int n = 0; while (true) { if (octal == 0) { break; } else { int temp = octal % 10; decimal += temp * Math.pow(8, n); octal = octal / 10; n++; } } return decimal; } }
Output: 85
That’s it!