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,

Also read – decimal to hexadecimal

Java convert decimal to octal using Integer.toOctalString()

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

public static String toOctalString(int i)

This method returns a string representation of the integer argument as an unsigned integer in base 8.

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


Java convert decimal to octal using custom code

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