# Java convert decimal to octal

Let’s learn java convert decimal to octal.

## Java convert decimal to octal

Write program to convert given decimal number to equivalent octal number is one of the frequently asked interview question.

Also read – binary to octal in java

In the below java program we need to convert given decimal number (base value 10) into octal number (base value 8).

To represent numeric value, decimal number system uses 0-9 digits and octal number system uses 0-7 digits.

There are two ways in decimal to octal conversion.

• using Integer.toOctalString() method.
• with our own logic.

public static String toOctalString(int i)

toOctalString() method returns a the string representation of the unsigned integer value represented by the argument in octal (base 8).

```import java.util.Scanner;
public class DecimalToOctal
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
String strOctal = Integer.toOctalString(number);
System.out.println("Octal number is: " + strOctal);
sc.close();
}
}

```

Output:

Octal number is: 27

Before going with our own logic first let’s see decimal to octal conversion algorithm.

```public class DecimalToOctalDemo
{
static String convertToOctal(int deci)
{
int remainder;
String strOctal = "";
char[] ch = {'0','1','2','3','4','5','6','7'};
while(deci > 0)
{
remainder = deci % 8;
strOctal = ch[remainder] + strOctal;
deci = deci / 8;
}
return strOctal;
}
public static void main(String[] args)
{
System.out.println("Octal of 11 is: " + convertToOctal(11));
System.out.println("Octal of 21 is: " + convertToOctal(21));
System.out.println("Octal of 31 is: " + convertToOctal(31));
}
}

```

Output:

Octal of 11 is: 13
Octal of 21 is: 25
Octal of 31 is: 37

Also read – decimal to binary in java

program convert decimal to octal using while loop

Let’s learn to convert decimal to octal using while loop.

```import java.util.Scanner;
public class UsingWhileLoop
{
public static void main(String[] args)
{
int decimal;
Scanner sc = new Scanner(System.in);
decimal = sc.nextInt();
int octalNumber = 0, a = 1;
while(decimal > 0)
{
octalNumber += a * (decimal % 8);
decimal = decimal / 8;
a = a * 10;
}
System.out.println("Octal number is: " + octalNumber);
sc.close();
}
}

```

Output: