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
 
This code creates a StringBuilder object called “octal” and an array of characters called “octalNumbers” which contains the digits 0-7. The code uses a while loop to continually divide the input integer by 8 and add the remainder to the “octal” StringBuilder, until the input integer is less than or equal to 0. The final result is returned as a string by calling the toString() method on the “octal” StringBuilder.
 
That’s it!
 
Happy coding!

Leave a Reply

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