What is the Integer.toOctalString method in Java?

The toOctalString method of the Integer class can be used to convert the int value to an octal string.

The octal is the base-8 number system, and uses the digits from 0 to 7.

Syntax

public static String toOctalString(int i);

This method returns an unsigned value in base 8 formatoctal format.

If the passed argument is negative, then the resultant octal value is equivalent to the octal value of 2^{32} + argument. For example, if the argument is -1:

toOctalString(-1) => toOctalString(Math.pow(2, 32) + (-1) );

Code

class IntToOctalString {
public static void main( String args[] ) {
int i = 8;
System.out.println("The octal value of " + i + " is : " + Integer.toOctalString(i));
int j = -1;
System.out.println("The octal value of " + j + " is : " + Integer.toOctalString(j));
}
}

Explanation

In the code above:

  • We created an int variable i and assigned 8 as a value to it. Then, we used the toOctalString method to convert the int to an octal string. The octal value of 8 is 10.

  • We then called the toOctalString method with a negative value as an argument:

int j = -1;
Integer.toOctalString(j);

If the argument is negative, before octal conversion internally, the argument is converted to 2^{32} + argument (2322^{32} = 4294967296). In our case, this is:

=> 4294967296 + (- 1)
=> 4294967296 - 1
=> toOcatlString(4294967295)
=> 37777777777

We will get 37777777777 as result.

Free Resources