Java Program to convert number from decimal to octal and vice-versa.
Objective
Write a Java program to convert a Decimal number to Octal and vice-versa.
Algorithm / Approach
- To convert Dec to Octal: Parse the string to an integer, then use
String.format("%o", deci)to get the Octal string. - To convert Octal to Dec: Read the octal string, and use
Integer.valueOf(oct, 8).
Test.java
import java.util.*;
class Test {
public static void main(String [] ar){
Scanner sc = new Scanner(System.in);
System.out.print("Value in Dec:");
String dec = sc.nextLine();
int deci = Integer.parseInt(dec);
String dectooct;
dectooct = String.format("%o",deci);
System.out.println("Oct : "+dectooct);
System.out.println("---------");
System.out.print("Value in Oct:");
String oct = sc.nextLine();
int octtodec = Integer.valueOf(oct,8);
System.out.println("Dec : "+octtodec);
}
}
Expected Output
Value in Dec:29 Oct : 35 ------------ Value in Oct:37 Dec : 31
Explanation of the Program
- Octal is a base-8 number system (using digits 0-7). It was heavily used in early computing (like Unix file permissions).
- The
%oformat specifier automatically formats a base-10 integer into its base-8 string representation.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)