Convert Octal to Decimal in Java

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
 
This code defines a static method named “getDecimalFromOctal” which takes an integer (in octal format) as input and returns an integer. Inside the method, it initializes variables “decimal” and “n” to 0. Then, it uses a while loop to continually divide the octal input by 10, add the remainder multiplied by 8 raised to the power of “n” to “decimal” and increment “n” by 1. The loop continues until the octal input becomes 0.
 
If you are looking to perform the reverse operation, check out this tutorial Convert Decimal to Octal in Java for detailed instructions.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *