# Java Program for Decimal to Octal

In the previous article, we have discussed Java Program for Decimal to Binary

## Java Program to Convert Decimal to Octal

Before jumping into the program directly, let’s first know about binary and decimal.

Decimal:

Decimal number mainly defines the base of 10 in the number system. This number is basically consists of  10(ten) single digits like 0,1,2,3,4,5,6,7,8 and 9 with base 10. It is also known as a position value system.

Example:

(183)10
(321)10

where (number)10, base is 10.

Octal:

Octal number basically defines the base of 8 in the number system. The number is specially consists of 0,1,2,3,4,5,6 and 7 so this number requires 3 bit to represent this octal number.

Example:

(534)8
(26)8

where (number)8 , base is 8.

Let’s see different ways to convert decimal to octal.

### Method-1: Java Program for Decimal to Octal By using Integer.toOctalString() method

In this approach by using the direct inbuilt method Integer.toOctalString() the decimal can be converted into octal. So directly passing the number as parameter to the method conversion takes place.

public class DecimalToOctal
{

public static void main(String args[])
{

//By Using the predefined Integer.toOctalString() method
//for converting decimal value into octal
System.out.println(Integer.toOctalString(85));
System.out.println(Integer.toOctalString(196));

}
}
Output:

125
304

### Method-2: Java Program for Decimal to Octal By using Custom logic

import java.util.*;

public class DecimalToOctal
{

//creating method for conversion so that we can use it many times

public static String toOctal(int decimal)
{
int rem; // for storing  remainder
String octal=""; //declareing variable to store octal
//declaring array of octal number
char octalchars[]={'0','1','2','3','4','5','6','7'};
//writing logic of decimal to octal conversion
while(decimal>0)
{
rem=decimal%8;
octal=octalchars[rem]+octal;
decimal=decimal/8;
}
return octal;
}

//driver method
public static void main(String args[])
{
//Calling custom method to get the octal number of given decimal value
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number for conversion decimal to octal = ");
int n = sc.nextInt();
System.out.println("Decimal to octal of "+n+" is: "+toOctal(n));
}
}
Output:

Enter a number for conversion decimal to octal = 8
Decimal to octal of 8 is: 10

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.

Related Java Programs: