Convert Octal Number to Decimal in Java

Exercise:

Write a Java Program to convert octal number to decimal number.

Click Here to View the Solution!
public class OctalToDecimal {
  
     public static void main(String[] args) {
         int octal = 105;
         int decimal = convertOctalToDecimal(octal);
         System.out.printf("%d in octal = %d in 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;
     }
 } 
Click Here to View the Output!
105 in octal = 69 in decimal
Click Here to View the Explanation!
  • This program deals with the transformation of an octal number into its decimal equivalent by employing convertOctalToDecimal() function.
  • In the initial stage an octal number having a value of ‘105’ is declared in the main function to be passed to convertOctalToDecimal() function as an argument.
  • The function convertOctalToDecimal() holds variables such as ‘octal’ as a parameter keeping the input number, ‘decimalNumber’ and ‘i’.
  • The ‘while’ condition indicates that the program will continue execution as long as the value of ‘octal’ variable is not equal to ‘0’.
  • The first step of the execution process is to calculate the remainder of the octal number to the base ‘10’ and taking its product with the powers of ‘8’ (initially 80).
  • The resultant values of the products are added to the previous value of variable ‘decimalNumber’.
  • The variable ‘i’ here keeps track of powers of ‘8’, being increased by ‘1’ with each pass.
  • The program halts its execution when the value of ‘octal’ becomes ‘0’, and returns ‘69’ (stored in ‘decimalNumber’) which is the decimal value for octal number ‘105’.
%d bloggers like this: