Decimal to octal in java

Hey guys!! Welcome to flower brackets blog. Today let us learn how to convert decimal to octal in java.

Decimal to Octal In Java

Below are the two ways to convert decimal number to octal number,

Using Integer.toOctalString()

Here we are using predefined method Integer.toOctalString() to convert decimal number to octal number in java,

Also read – decimal to hexadecimal

public class DecimalToOctalSample 
{
   public static void main(String[] args) 
   {
      // using predefined Integer.toOctalString()
      System.out.println(Integer.toOctalString(50)); 
      System.out.println(Integer.toOctalString(18)); 
      System.out.println(Integer.toOctalString(100));
   }
}

Output:

62
22
144


Using method

public class DecimalToOctal
{
   public static String convertOctal(int decimal)
   { 
      int remainder; 
      String strOctal = "";
      char octal[] = {'0','1','2','3','4','5','6','7'}; 
      while(decimal > 0) 
      { 
         remainder = decimal % 8; 
         strOctal = octal[remainder] + strOctal; 
         decimal = decimal / 8; 
      } 
      return strOctal; 
   }

   public static void main(String[] args)
   { 
      System.out.println(convertOctal(50)); 
      System.out.println(convertOctal(18)); 
      System.out.println(convertOctal(100));
   }
}

Output:

62
22
144


Related Posts