Java Program to Convert Decimal to Octal Number
Integer.toOctalString(decimalNumber) or by repeatedly dividing the number by 8 and collecting remainders.Examples
How to Think About It
Algorithm
Code
public class DecimalToOctal { public static void main(String[] args) { int decimalNumber = 65; String octalNumber = Integer.toOctalString(decimalNumber); System.out.println("Octal of " + decimalNumber + " is: " + octalNumber); } }
Dry Run
Let's trace converting decimal 65 to octal using repeated division.
Divide 65 by 8
65 ÷ 8 = 8 remainder 1 (rightmost octal digit)
Divide 8 by 8
8 ÷ 8 = 1 remainder 0 (next octal digit)
Divide 1 by 8
1 ÷ 8 = 0 remainder 1 (leftmost octal digit)
| Decimal Number | Divide by 8 | Quotient | Remainder (Octal Digit) |
|---|---|---|---|
| 65 | 65 ÷ 8 | 8 | 1 |
| 8 | 8 ÷ 8 | 1 | 0 |
| 1 | 1 ÷ 8 | 0 | 1 |
Why This Works
Step 1: Using Integer.toOctalString
Java's built-in method Integer.toOctalString() converts decimal to octal by handling the division and remainder internally.
Step 2: Manual division method
Dividing the decimal number by 8 repeatedly and collecting remainders builds the octal number from right to left.
Step 3: Reversing remainders
Since the first remainder is the least significant digit, reversing the collected digits gives the correct octal representation.
Alternative Approaches
public class DecimalToOctalManual { public static void main(String[] args) { int decimal = 65; StringBuilder octal = new StringBuilder(); int number = decimal; if (number == 0) { octal.append('0'); } while (number > 0) { int remainder = number % 8; octal.insert(0, remainder); number /= 8; } System.out.println("Octal of " + decimal + " is: " + octal); } }
public class DecimalToOctalRadix { public static void main(String[] args) { int decimal = 65; String octal = Integer.toString(decimal, 8); System.out.println("Octal of " + decimal + " is: " + octal); } }
Complexity: O(log n) time, O(log n) space
Time Complexity
The conversion requires dividing the number by 8 repeatedly until it reaches zero, which takes about log base 8 of n steps.
Space Complexity
Storing the octal digits requires space proportional to the number of digits, which is also about log base 8 of n.
Which Approach is Fastest?
Using built-in methods like Integer.toOctalString() or Integer.toString(number, 8) is fastest and less error-prone compared to manual division.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer.toOctalString() | O(log n) | O(log n) | Quick and simple conversion |
| Manual division with loop | O(log n) | O(log n) | Learning and understanding conversion process |
| Integer.toString(number, 8) | O(log n) | O(log n) | Concise alternative to toOctalString |
Integer.toOctalString() for quick and reliable decimal to octal conversion in Java.