Java Programs›Numbers›Convert Decimal to Octal

Convert Decimal to Octal in Java

beginner·  Numbers  ·  Number Conversion

Problem

Octal is base 8, using only the digits 0 to 7; each place is worth a power of eight, so 310 in octal means 3×64 + 1×8 + 0 = 200.

Given a non-negative integer, print its octal (base-8) representation.

Input
200
Output
310

Java Program

Java
public class DecimalToOctal { public static void main(String[] args) { int number = 200; if (number == 0) { System.out.println("Octal of 0: 0"); return; } StringBuilder octal = new StringBuilder(); int n = number; while (n > 0) { octal.append(n % 8); // each remainder is one octal digit, 0 to 7 n /= 8; } System.out.println("Octal of " + number + ": " + octal.reverse()); } }

Output

Octal of 200: 310

Core Logic

The same remainder method used for binary works for any base: dividing by 8 peels off the lowest octal digit each time.

How It Works
  1. 1n % 8 is the current lowest octal digit, always between 0 and 7.
  2. 2n /= 8 removes that digit.
  3. 3Digits are appended lowest first and reversed at the end.
  4. 4The value 0 is printed directly, since the loop would produce an empty string for it.
200 → remainder 0, 25 → 1, 3 → 3. Reversed, the digits read 310.
💡

Key Point: Octal still shows up in Unix file permissions — chmod 755 is three octal digits, each encoding read/write/execute bits.

Complexity
Time Complexity: O(log n)Space Complexity: O(log n)

Why: The value shrinks by a factor of 8 per step, so there is one iteration and one stored character per octal digit.

Key Concepts

while loopmodulo operatorStringBuilder.reverse()

Approach 2: Using Integer.toOctalString()

Java
public class DecimalToOctalBuiltIn { public static void main(String[] args) { int number = 200; System.out.println("Octal of " + number + ": " + Integer.toOctalString(number)); System.out.println("Same, via toString: " + Integer.toString(number, 8)); // any radix from 2 to 36 } }

Output

Octal of 200: 310 Same, via toString: 310

Core Logic

Java provides a dedicated octal method, plus a general toString overload that converts to any base from 2 to 36.

How It Works
  1. 1Integer.toOctalString(200) returns "310".
  2. 2Integer.toString(200, 8) gives the same result through the general radix method.
  3. 3For negative numbers the two differ: toOctalString shows the unsigned bit pattern, while toString keeps a minus sign.
Both calls print 310 for 200.
💡

Key Point: Knowing Integer.toString(value, radix) covers every base conversion with one method name.

Complexity
Time Complexity: O(log n)Space Complexity: O(log n)

Why: One character is produced per octal digit.

Key Concepts

Integer.toOctalString()Integer.toString(int, radix)

Interview Questions

Where is octal still used?

Mainly in Unix file permissions, such as chmod 644.

How does Java write an octal literal?

With a leading zero: 0755 is octal, which is 493 in decimal.

Learn the Concept

Related Programs