Convert Decimal to Octal in Java
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.
Java Program
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
Core Logic
The same remainder method used for binary works for any base: dividing by 8 peels off the lowest octal digit each time.
- 1
n % 8is the current lowest octal digit, always between 0 and 7. - 2
n /= 8removes that digit. - 3Digits are appended lowest first and reversed at the end.
- 4The value 0 is printed directly, since the loop would produce an empty string for it.
310.Key Point: Octal still shows up in Unix file permissions — chmod 755 is three octal digits, each encoding read/write/execute bits.
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
Approach 2: Using Integer.toOctalString()
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
Core Logic
Java provides a dedicated octal method, plus a general toString overload that converts to any base from 2 to 36.
- 1
Integer.toOctalString(200)returns"310". - 2
Integer.toString(200, 8)gives the same result through the general radix method. - 3For negative numbers the two differ:
toOctalStringshows the unsigned bit pattern, whiletoStringkeeps a minus sign.
310 for 200.Key Point: Knowing Integer.toString(value, radix) covers every base conversion with one method name.
Why: One character is produced per octal digit.
Key Concepts
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.