On this section we will be discussion on java decimal to octal conversion. We have already posted an article how to convert octal to decimal in java, and as we have already pointed out decimal is of base 10 while when we say octal numbers are those integers which is at base 8. Luckily in java we have a ready API which can readily handle the conversion using the toOctalString of the Integer class. This method the octal equivalent of the integer passed on this method.
Decimal to Octal Conversion in java
This sample source code get the decimal user input on the console and convert it using the toOctalString. Validating the user input was also in place to handle exception. Finally as required by the Scanner class, we will call the close method of this class. If not properly handled, once an invalid input from the console has been read, InputMismatchException error will be thrown.
package com.javatutorialhq.tutorial; import java.util.InputMismatchException; import java.util.Scanner; /* * Example java source code to convert Decimal to octal */ public class DecimalToOctal { public static void main(String[] args) { System.out.print("Input:"); // getting the value from the console Scanner s = new Scanner(System.in); try{ // using the scanner to get decimal input Integer decimalVal = s.nextInt(); // convert the Decimal value to Octal String outputOctal = Integer.toOctalString(decimalVal); System.out.println("Octal Value:"+outputOctal); } catch(InputMismatchException ie){ System.out.println("Invalid Decimal Input"); } finally{ // closing the scanner object s.close(); } } }
Sample Output in running the Decimal to Octal Converter
Input:121 Octal Value:171