Java Program to convert number from decimal to binary and vice-versa.
Objective
Write a Java program to convert a Decimal number to Binary and vice-versa.
Algorithm / Approach
- To convert Dec to Bin: Parse the decimal string to an integer, then use
Integer.toBinaryString(deci). - To convert Bin to Dec: Read the binary string, and use
Integer.valueOf(bin, 2).
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 dectobin;
dectobin = Integer.toBinaryString(deci);
System.out.println("Bin : "+dectobin);
System.out.println("---------");
System.out.print("Value in Bin:");
String bin = sc.nextLine();
int bintodec = Integer.valueOf(bin,2);
System.out.println("Dec : "+bintodec);
}
}
Expected Output
Value in Dec: 15 Bin : 1111 ----------- Value in Bin: 101 Dec : 5
Explanation of the Program
- Binary is a base-2 number system (using only 0 and 1) used by computer processors.
- Instead of writing complex division loops to manually calculate the binary representation, Java provides
toBinaryString()as a convenient utility.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)