**Exercise**:

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

**Click Here to View the Solution! **

```
public class OctalToBinary {
public static void main(String[] args) {
int octal = 89;
long binary = convertOctalToBinary(octal);
System.out.printf("%d in octal = %d in binary", octal, binary);
}
public static long convertOctalToBinary(int octalNumber)
{
int decimalNumber = 0, i = 0;
long binaryNumber = 0;
while(octalNumber != 0)
{
decimalNumber += (octalNumber % 10) * Math.pow(8, i);
++i;
octalNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
binaryNumber += (decimalNumber % 2) * i;
decimalNumber /= 2;
i *= 10;
}
return binaryNumber;
}
}
```

**Click Here to View the Output! **

89 in octal = 1001001 in binary

**Click Here to View the Explanation! **

- This program deals with finding out Binary equivalent to an Octal number as depicted by
`convertOctalToBinary()`

function. - It has two segments, where first segment calculates decimal equivalent to the octal number ‘89’.
- During each iteration of the first ‘while’ condition, the remainder for the given octal number is calculated to the base ‘10’ and is then multiplied with exponential value of (8
^{0}= 1). The resultant value (9 * 8^{0}= 9) is added to ‘`decimalNumber`

’. - In the next pass ‘i’ becomes ‘1’, and is multiplied by the ‘8’ (89 / 10 = 8) as the data type is ‘int’). Now (8 * 8
^{1 }= 64) value is added to the previous value ‘9’ and becomes ’64 + 9 = 73). - This value ‘73’ is decimal equivalent to ‘89’, and will be converted into binary form by the second ‘while’ condition.
- Here the remainder for the decimal number is calculated to the base ‘2’, and is then multiplied by ‘i’ which is now equal to ‘1’.
- As usual the resultant product value is added to ‘binaryNumber’. (73 % 2 = 1) * 1
- After the execution of this loop calculated binary value ‘
`1001001`

’ of the given octal number ‘`89`

’, the program terminates.