Convert Decimal to Octal in Java

In the previous lesson, we covered the conversion of Octal to Decimal. In this post, you will learn how to convert Decimal to Octal in Java.

We can do that in the following ways:

  • Using the Integer.toOctalString() method
  • With a custom logic

Convert Decimal to Octal in Java using the Integer.toOctalString() method

Integer class has a method toOctalString(int i) that we can use to parse decimal to octal. This method returns a string representation of the integer argument as an unsigned integer in base 8.

Example

class Test {

  public static void main(String[] args) {

    String octal = Integer.toOctalString(43);

    System.out.println("Octal: " + octal);
  }
}
Output: Octal: 53

Parse Decimal to Octal with a custom logic

We can also implement our custom logic without using predefined methods. Like in the following example:

class Test {

  public static void main(String[] args) {

    String octal = convertToOctal(85);

    System.out.println(octal);
  }

  public static String convertToOctal(int decimal) {
    int reminder;
    StringBuilder octal = new StringBuilder();

    char[] octalNumbers = {'0', '1', '2', '3', '4', '5', '6', '7'};

    while (decimal > 0) {
      reminder = decimal % 8;
      octal.insert(0, octalNumbers[reminder]);
      decimal = decimal / 8;
    }

    return octal.toString();
  }
}
Output: 125
 
That’s it!
 
Happy coding!

Leave a Reply

Your email address will not be published.