Static method – java convert decimal to octal | vice versa

Let’s learn static method – java convert decimal to octal.

Static method – java convert decimal to octal

Write a java program to convert a decimal number to octal number is one of the common java interview question.

In this post let’s learn decimal to octal conversion using static method. In order to convert decimal to octal first user enters a decimal number. Then this decimal number is divided by 8.

static method - java convert decimal to octal

After dividing decimal number by 8 store the remainder. Now we have to repeat previous steps until number is divided.

Also read – decimal to hexadecimal conversion in java

In the last step print the reverse of the remainder we got while dividing by 8 in the console.

This reversed octal number is equivalent to decimal number.

Decimal to octal conversion

DecimalOctal
00
11
22
33
44
55
66
77
810
911
1012
1113
1214
1315
1416
1517
1620

Here’s how to write a java program to convert a decimal number to octal number.

import java.util.Scanner;
public class DecimalToOctal
{
   static int a = 1;
   public static void main(String[] args)
   {
      int decimal;
      Scanner sc = new Scanner(System.in);   
      System.out.println("Please enter a decimal number : ");
      decimal = sc.nextInt();
      System.out.println("The octal number is : ");
      int[] oct = convertToOctal(decimal); 
      for(int x = a - 1; x > 0; x--)
      {
         System.out.print(oct[x]);
      }
      sc.close();
   }
   static int[] convertToOctal(int oct) 
   {
      int y[] = new int[50];
      while(oct != 0)
      {
         y[a++] = oct % 8;
         oct = oct / 8;
      }
      return y;
   }
}


Output:

Please enter a decimal number : 100
The octal number is : 144


Click here to learn vice versa of above java program with explanation.

Also read – convert decimal to binary in java

Also read – java program to convert decimal to binary and vice versa


Java program to convert decimal to octal using while loop

Now let’s see how to convert decimal to octal using while loop.

import java.util.Scanner;
public class DecimalToOctalUsingWhileLoop 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter decimal number: ");
      int decimal = sc.nextInt();
      int octal = 0, remainder, temp, a = 1;
      temp = decimal;
      // here loop continues until temp to 0
      while(temp > 0)
      {
         // getting the remainder
         remainder = temp % 8;
         octal = octal + remainder * a;
         temp = temp / 8;
         a = a * 10;
      } 
      System.out.println("Convert decimal to octal using while loop: " + octal);
      sc.close();
   }
}


Output:

Please enter decimal number: 23
Convert decimal to octal using while loop: 27