Java convert octal to decimal

Today we are going to learn java convert octal to decimal.

java convert octal to decimal

In java, to convert octal to decimal parseInt() method of Integer class is used,

public static int parseInt(String s, int radix) throws NumberFormatException

Also read – merge sort in java

Parses the string argument as a signed integer in the radix specified by the second argument.

However, if the String does not contain a parsable int NumberFormatException is thrown. Here’s java program to convert octal number to decimal number,

public class OctalToDecimalDemo 
{
   public static void main(String[] args) 
   { 
      String strOctal = "141"; 
      // converting octal to decimal using Integer.parseInt 
      int decimal = Integer.parseInt(strOctal, 8); 
      System.out.println(decimal);
   }
}

Output:

java convert octal to decimal


Meanwhile we can execute above java program using method. Here’s the code,

public class OctalCode 
{
   public static int octalToDecimal(int octalNumber)
   { 
      int decimal = 0; 
      int num = 0; 
      while(true)
      { 
         if(octalNumber == 0)
         { 
            break; 
         }
         else
         { 
            int temp = octalNumber % 10; 
            decimal += temp * Math.pow(8, num); 
            octalNumber = octalNumber / 10; 
            num++; 
         } 
      } 
      return decimal; 
   }

   public static void main(String[] args) 
   { 
      System.out.println("141 octal is : " + octalToDecimal(141)); 
      System.out.println("230 octal is : " + octalToDecimal(230)); 
      System.out.println("100 octal is : " + octalToDecimal(100));
   }
}

Output:

141 octal is : 97
230 octal is : 152
100 octal is : 64

Related Posts