Java Convert Octal to Decimal

In this source code example, we will write a Java program that converts any Octal number to a Decimal number.
Check out Java 8 examples at Java 8 Examples
Checkout all Java programs at 100+ Java Programs 

Java Convert Octal to Decimal

This class converts any Octal number to a Decimal number:
package net.sourcecodeexamples.java.Conversions;

import java.util.Scanner;

/**
 * Converts any Octal Number to a Decimal Number
 * 
 * @author sourcecodeexamples.net
 *
 */
public class OctalToDecimal {

    /**
     * Main method
     * 
     * @param args Command line arguments
     */
    public static void main(String args[]) {
        try (Scanner sc = new Scanner(System.in)) {
            System.out.print("Octal Input: ");
            String inputOctal = sc.nextLine();
            int result = convertOctalToDecimal(inputOctal);
            if (result != -1)
                System.out.println("Result convertOctalToDecimal : " + result);
        }
    }

    /**
     * This method converts an octal number to a decimal number.
     * 
     * @param inputOctal The octal number
     * @return The decimal number
     */
    public static int convertOctalToDecimal(String inputOctal) {

        try {
            // Actual conversion of Octal to Decimal:
            Integer outputDecimal = Integer.parseInt(inputOctal, 8);
            return outputDecimal;
        } catch (NumberFormatException ne) {
            // Printing a warning message if the input is not a valid octal
            // number:
            System.out.println("Invalid Input, Expecting octal number 0-7");
            return -1;
        }
    }
}

Output

Octal Input: 121
Result convertOctalToDecimal : 81
Check out Java 8 examples at Java 8 Examples
Checkout all Java programs at 100+ Java Programs 

Comments