In this guide, we will discuss the following two ways to convert decimal to octal in Java.
- Using predefined method toOctalString(int num) of Integer class
- Writing a custom logic for decimal to octal conversion
Example 1: Decimal to Octal using toOctalString() method
The Integer.toOctalString(int i)
method accepts integer number as argument and returns the equivalent octal number as string after conversion. The syntax of toOctalString()
is as follows:
public static String toOctalString(int i)
Let’s write a java program for conversion:
public class JavaExample{ public static void main(String args[]){ int decimalNumber = 80; String octalNumber = Integer.toOctalString(decimalNumber); System.out.println("Decimal to Octal: "+octalNumber); } }
Output:
Decimal to Octal: 120
Example 2: Conversion without using toOctalString()
Here, we are not using the predefined method for conversion. We have used a logic to convert the given decimal number to octal.
class DecimalToOctalExample { public static void main(String args[]) { int num = 101; // For storing remainder int rem; // For storing result String str=""; // Digits in Octal number system char dig[]={'0','1','2','3','4','5','6','7'}; while(num>0) { rem=num%8; str=dig[rem]+str; num=num/8; } System.out.println("Decimal to Octal: "+str); } }
Output:
Decimal to Octal: 145
Leave a Reply