Java convert octal to decimal

Let’s learn java convert octal to decimal.

java convert octal to decimal

Java convert octal to decimal

To convert octal to decimal in java parseInt() method of Integer class is used. Syntax for Integer.parseInt() method is as follows,

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

Integer.parseInt() method returns the integer represented by the string argument in the specified radix.

Also read – hexadecimal to decimal in java

However, if the String does not contain a parsable int NumberFormatException is thrown.

Octal to decimal converter

Here’s how to convert from octal to decimal,

Octal base 8 Decimal base 10
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
10 8
11 9
12 10
13 11
14 12
15 13
16 14
17 15
20 16
30 24
40 32
50 40
60 48
70 56
100 64

For example: 1418 = 1×82 + 4×81 + 1×80 = 97

Here’s java program to convert octal to binary,

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

Similarly we can convert an octal value to an equivalent decimal value using Scanner class. Here we get octal value from user. Let’s see java program,

import java.util.Scanner;

public class OctalToDecimalDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter octal value: ");
      String strOctal = sc.nextLine();
      // octal to decimal using Integer.parseInt()
      int decimal = Integer.parseInt(strOctal, 8);
      System.out.println("Java octal to decimal conversion " + strOctal + " is: " + decimal);
      sc.close();
   }
}



Output:

Please enter octal value: 141
Java octal to decimal conversion 141 is: 97

Meanwhile let’s see java program to convert octal to binary using functions. Here’s the java program,

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

Also read – decimal to binary in java

Click here to learn vice versa of above java program to convert octal to binary.