- 1Convert Decimal to Binary in Java
- 2Convert Binary to Decimal in Java
- 3Convert Decimal to Octal in Java
- 4Convert Octal to Decimal in Java
- 5Convert Decimal to Hexadecimal in Java
- 6Convert Hexadecimal to Decimal in Java
- 7Convert Binary to Hexadecimal in Java
- 8Convert Hexadecimal to Binary in Java
- 9Convert Octal to Binary in Java
- 10Convert Temperature from Celsius to Fahrenheit in Java
- 11Convert Kilometers to Miles, Meters, and Centimeters in Java
- 12Convert a String to Uppercase and Lowercase in Java
Convert Decimal to Octal in Java
Topic: Convert Decimal to Octal
In this program, we’ll convert a number from decimal (base 10) to octal (base 8). Decimal numbers use digits 0–9, while octal numbers use digits 0–7.
For example, the decimal number 10 becomes 12 in octal. This type of conversion is common in computer science, especially in low-level programming and memory address calculations.
We’ll use a simple loop that repeatedly divides the number by 8 and stores the remainders, which together form the octal number.
Examples
Example 1:
Input: 10
Output: 12
Explanation: 10 ÷ 8 = 1 remainder 2 → 1 ÷ 8 = 0 remainder 1 → Octal = 12
Example 2:
Input: 64
Output: 100
Explanation: 64 ÷ 8 = 8 rem 0 → 8 ÷ 8 = 1 rem 0 → 1 ÷ 8 = 0 rem 1 → Octal = 100
Example 3 (Edge Case):
Input: 0
Output: 0
Explanation: 0 in decimal is 0 in octal.
Interviewer Expectations
The interviewer wants to see if you can:
- Understand base conversions (decimal to octal)
- Use loops and arithmetic operators
- Build the result by processing remainders in reverse order
- Write clean and readable code
Approach
To convert a decimal number to octal:
- Initialize an empty string or use an array to store remainders.
- Keep dividing the number by 8 until it becomes 0.
- Store the remainders (in reverse order) to form the octal number.
Dry Run:
Decimal: 10
10 ÷ 8 = 1 remainder 2 1 ÷ 8 = 0 remainder 1 Octal = 12 (read remainders from bottom to top)
Java Program
public class DecimalToOctal {
public static void main(String[] args) {
int decimal = 10;
String octal = "";
while (decimal > 0) {
int remainder = decimal % 8;
octal = remainder + octal;
decimal = decimal / 8;
}
System.out.println("Octal representation: " + octal);
}
}
Octal representation: 12
Possible Followup Questions with Answers
Q1: Can I use built-in methods for this conversion?
Yes. Java provides Integer.toOctalString()
which converts a decimal to octal directly:
int decimal = 10;
System.out.println(Integer.toOctalString(decimal)); // Output: 12
Q2: How would you convert octal back to decimal?
You can use Integer.parseInt(octalString, 8)
to convert an octal string to decimal:
String octal = "12";
int decimal = Integer.parseInt(octal, 8); // Output: 10
Q3: What if the input is 0?
The output will also be 0. You can handle this with a special case at the beginning of the program:
if (decimal == 0) {
System.out.println("0");
return;
}
Comments
Loading comments...