English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/)

Java Reader/Writer

Java Other Topics

Java Program for Octal and Decimal Conversion

Comprehensive Java Examples

In this program, you will learn how to use Java functions to convert octal numbers to decimal numbers and vice versa.

Example1Program to convert decimal to octal

public class DecimalOctal
    public static void main(String[] args) {
        int decimal = 78;
        int octal = convertDecimalToOctal(decimal);
        System.out.printf("%d Decimal = %d Octal", decimal, octal);
    }
    public static int convertDecimalToOctal(int decimal)
    {
        int octalNumber = 0, i = 1;
        while (decimal != 0)
        {
            octalNumber += (decimal % 8) * i;
            decimal /= 8;
            i *= 10;
        }
        return octalNumber;
    }
}

When running the program, the output is:

78 Decimal = 116 Octal

This conversion occurs as:

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

Example2Program to convert octal to decimal

public class OctalDecimal {}}
    public static void main(String[] args) {
        int octal = 116;
        int decimal = convertOctalToDecimal(octal);
        System.out.printf("%d Octal = %d Decimal", octal, decimal);
    }
    public static int convertOctalToDecimal(int octal)
    {
        int decimalNumber = 0, i = 0;
        while(octal != 0)
        {
            decimalNumber += (octal % 10) * Math.pow(8, i);
            ++i;
            Octal/=10;
        }
        return decimalNumber;
    }
}

When running the program, the output is:

116 Octal = 78 Decimal

This conversion occurs as:

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

Comprehensive Java Examples