Octal To Decimal Conversion Java Program

By | 2018-03-21T21:12:36+05:30 June 19th, 2016|java programs|

Here we are going to write a program on conversion of Octal To Decimal Numbers in Java.

Octal To Decimal Java Program :


import java.util.Scanner;

public class ConvertOctalToDecimal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a Oct Number :");
        String input = sc.nextLine();
        convertOctalToDecimal(input);
    }
    
    public static int convertOctalToDecimal(String octal) {
        int decimal = 0;
        int power = 0;
        if (octal != null && !octal.isEmpty()) {
            if (isOctal(octal)) {
                if (octal.length() > 1) {
                    int number = Integer.parseInt(octal);

                    while (number > 0) {
                        decimal = decimal + (number % 10) * (int) Math.pow(8, power);
                        power++;
                        number /= 10;
                    }
                } else {
                    decimal = Integer.valueOf(octal);
                }
            } else {
                System.out.println("The number is not an octal format");
            }
            System.out.println("The decimal number is: " + decimal);
        }

        return decimal;
    }
    public static boolean isOctal(String octal) {

        boolean isOctal = false;

        if (octal != null && !octal.isEmpty()) {
            int number = Integer.parseInt(octal);

            while (number > 0) {
                if (number % 10 <= 7) {
                    isOctal = true;
                } else {
                    isOctal = false;
                    break;
                }
                number /= 10;
            }
        }

        return isOctal;
    }

}

Output :

Enter a Oct Number :  20
The decimal number is: 16
Oct is : 16

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment