LAST UPDATED: DECEMBER 1, 2020
How to convert Java Octal to Decimal
In Java, Octal value can be converted into Decimal value either by using Integer.parseInt() method or own custom code. Let's see the examples.
1. Integer.parseInt()
method
The parseInt() method is a part of Integer class which converts the string into an int in accordance with the specified radix.
Example 1:
Here, the octal string values are converted into decimal values by using the parseInt()
method. See the example below.
public class StudyTonight
{
public static void main(String args[])
{
String o1 = "75";
String o2 = "-56573";
String o3 = "336";
int d1 = Integer.parseInt(o1,8);
int d2 = Integer.parseInt(o2,8);
int d3 = Integer.parseInt(o3,8);
System.out.println("Decimal value is : " +d1);
System.out.println("Decimal value is : " +d2);
System.out.println("Decimal value is : " +d3);
}
}
Decimal value is : 61
Decimal value is : -23931
Decimal value is : 222
Example 2:
The octal values can be converted into decimals using custom logic. This is useful when you don't want to use any built-in method.
public class StudyTonight
{
public static int decimalconvt(int oct)
{
int dec = 0;
int n = 0;
while(true)
{
if(oct == 0)
{
break;
}
else
{
int tmp = oct%10;
dec += tmp*Math.pow(8, n);
oct = oct/10;
n++;
}
}
return dec;
}
public static void main(String args[])
{
System.out.println("Decimal of 101 is: " +decimalconvt(101));
System.out.println("Decimal of 1756 is: " +decimalconvt(1756));
System.out.println("Decimal of -1743 is: " +decimalconvt(-1743));
}
}
Decimal of 101 is: 65
Decimal of 1756 is: 1006
Decimal of -1743 is: -995