Java convert decimal to octal

Today let us learn java convert decimal to octal.

java convert decimal to octal

Java program for decimal to octal conversion

To convert decimal to octal java there are the two ways,

Also read – decimal to hexadecimal

1. using predefined method Integer.toOctalString(),

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 DecimalToOctal
{
   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


2. 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