Java Program to Convert Octal Number to Decimal and vice-versa

In this program, you’ll learn to convert octal number to a decimal number and vice-versa using functions in Java.

Example 1: Program to Convert Decimal to Octal

  1. public class DecimalOctal {
  2. public static void main(String[] args) {
  3. int decimal = 78;
  4. int octal = convertDecimalToOctal(decimal);
  5. System.out.printf("%d in decimal = %d in octal", decimal, octal);
  6. }
  7. public static int convertDecimalToOctal(int decimal)
  8. {
  9. int octalNumber = 0, i = 1;
  10. while (decimal != 0)
  11. {
  12. octalNumber += (decimal % 8) * i;
  13. decimal /= 8;
  14. i *= 10;
  15. }
  16. return octalNumber;
  17. }
  18. }

When you run the program, the output will be:

78 in decimal = 116 in octal

This conversion takes place as:

8 | 78
8 | 9 -- 6
8 | 1 -- 1
8 | 0 -- 1
(116)

Example 2: Program to Convert Octal to Decimal

  1. public class OctalDecimal {
  2. public static void main(String[] args) {
  3. int octal = 116;
  4. int decimal = convertOctalToDecimal(octal);
  5. System.out.printf("%d in octal = %d in decimal", octal, decimal);
  6. }
  7. public static int convertOctalToDecimal(int octal)
  8. {
  9. int decimalNumber = 0, i = 0;
  10. while(octal != 0)
  11. {
  12. decimalNumber += (octal % 10) * Math.pow(8, i);
  13. ++i;
  14. octal/=10;
  15. }
  16. return decimalNumber;
  17. }
  18. }

When you run the program, the output will be:

116 in octal = 78 in decimal

This conversion takes place as:

1 * 82 + 1 * 81 + 6 * 80 = 78