Convert Decimal to Octal Number in Java

Exercise:

Write a Java Program to convert decimal to octal number.

Click Here to View the Solution!
public class DecimalToOctal {
  
     public static void main(String[] args) {
         int decimal = 69;
         int octal = convertDecimalToOctal(decimal);
         System.out.printf("%d in decimal = %d in octal", decimal, octal);
     }
  
     public static int convertDecimalToOctal(int decimal)
     {
         int octalNumber = 0, i = 1;
  
         while (decimal != 0)
         {
             octalNumber += (decimal % 8) * i;
             decimal /= 8;
             i *= 10;
         }
  
         return octalNumber;
     }
 } 
Click Here to View the Output!
69 in decimal = 105 in octal
Click Here to View the Explanation!
  • This program transforms a decimal number into an octal number by employing convertDecimalToOctal() function.
  • In the initial stage, an integer having a value of ‘69’ is declared in the main function passed as an argument to convertDecimalToOctal() function.
  • The function possesses three variables: ‘decimal’ as a parameter, ‘octalNumber’ and ‘i’.
  • The ‘while’ condition within the function states that the execution will continue as long as the value of ‘decimal’ is not equal to ‘0’.
  • The process of converting to octal number is same as binary number; the only difference is the base i.e. ‘8’ in this case.
  • In the first statement of ‘while’ condition, the remainder for the decimal number is calculated to the base ‘8’ and is taken product with ‘i’.
  • During each step, the resultant value is stored into ‘octalNumber’ variable.
  • In the second statement of while condition the number is divided by ‘8’ for the next pass.
  • The third statement of ‘while’ condition changes value of ‘i’ by taking product with ‘10’, in each step.
  • Once the value of ‘number’ tends to be equal to ‘0’, the ‘while’ condition becomes ‘false’ and terminates the program; returning a ‘105’ which is the octal value for the given number =69.
%d bloggers like this: