How do I convert decimal to octal?

From the code snippet below you will learn how to convert decimal to an octal string and converting back from a string of octal number to decimal. For the first conversion we can utilize the Integer.toOctalString() method. This method takes an integer number and will return the string that represent the corresponding octal number.

To convert back from octal string to decimal number we can use the Integer.parseInt() method. Which require two parameter, a string that represent an octal number, and the radix which is 8 from octal number.

package org.kodejava.lang;

public class IntegerToOctalExample {
    public static void main(String[] args) {
        int integer = 1024;
        // Converting integer value to octal string representation.
        String octal = Integer.toOctalString(integer);
        System.out.printf("Octal value of %d is '%s'.\n", integer, octal);

        // Now we converting back from octal string to integer
        // by calling Integer.parseInt and passing 8 as the radix.
        int original = Integer.parseInt(octal, 8);
        System.out.printf("Integer value of octal '%s' is %d.%n", octal, original);

        // When for formatting purposes we can actually use printf
        // or String.format to display an integer value in other
        // format (o = octal, h = hexadecimal).
        System.out.printf("Octal value of %1$d is '%1$o'.\n", integer);

Here is the result of our program.

Octal value of 1024 is '2000'.
Integer value of octal '2000' is 1024.
Octal value of 1024 is '2000'.