Decimal to Octal Program in Java
Advertisements
Convert Decimal to Octal Program in Java
There are two way to convert decimal number into octal number, which is given below;
- Using predefined method Integer.toOctalString(int num)
- Writing our own logic for conversion
Convert Decimal to Octal in Java
import java.util.Scanner; class DecimalToOctal { public static void main(String args[]) { Scanner input = new Scanner( System.in ); System.out.print("Enter a decimal number : "); int num =input.nextInt(); String octalString = Integer.toOctalString(num); System.out.println("Method 1: Decimal to octal: " + octalString); } }
Output
Enter a decimal number : 123 Decimal to octal: 173
Code Explanation
Using predefined method toOctalString(int) Pass the decimal number to this method and it would return the equivalent octal number.
Convert Decimal to Octal in Java
import java.util.Scanner; class DecimalToOctal { public static void main(String args[]) { Scanner input = new Scanner( System.in ); System.out.print("Enter a decimal number : "); int num =input.nextInt(); // 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
Enter a decimal number : 123 Decimal to octal: 173
Syntax to compile and run java program
Syntax
for compile -> c:/>javac DecimalToOctal.java for run -> c:/>java DecimalToOctal
Google Advertisment