Decimal to octal conversion using Java

Decimal to octal conversion using java :

 

In this article we will create a java program for converting a decimal number to its octal form. For this purpose we need to ask a decimal number from user and convert that decimal number to its octal equivalent form and then print the converted number on to the screen.
 
For conversion, we divide the decimal number by 8 and get the quotient for the next iteration and continuously store the remainder value in an array in reverse order till the decimal number is greater than 0. For better understanding with an example just have a look towards the diagram shown at the right.
Decimal to octal conversion using Java

Working :

Step 1 : Ask the user to enter a decimal number.

Step 2 : Declare an array and a variable for pointing index value of the array.

Step 3 : Use  the while loop till decimal number entered by user is greater than 0.

Step 4 : Divide the decimal number by 8 and store the remainder in the array and update the decimal number with the quotient.

Step 5 : Repeat the steps 3 and 4 till the decimal number is greater than 0.

Step 6 : Print the array in reverse order.

Code in Java :

//Java program to convert decimal number to octal number
import java.util.Scanner;
public class Decimal_To_Octal
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a Decimal number : ");
int decimal = sc.nextInt();
//integer array for storing octal digits
int octal[] = new int[20];
int i = 0;
//writing logic for the conversion
while(decimal > 0)
{
int r = decimal % 8;
octal[i++] = r;
decimal = decimal/8;
}
//printing result
System.out.print("Octal number : ");
for(int j = i-1 ; j >= 0 ; j--)
System.out.print(octal[j]);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a Decimal number : 147
Octal number : 223