top of page
Click here to go to the home page of AskTheCode.

Binary to Decimal and Decimal to Binary in Java | AskTheCode

Team ATC

Java program for user driven Binary to Decimal and Decimal to Binary conversion | Java Solutions

 

Problem:

Write a Java method that accepts a binary number and converts it to decimal, then display the result.

Sample output:

Enter the binary number:

110

6

Press 1 perform Decimal to Binary conversion:

1

Enter the decimal number:

14

1110

 

Code:

import java.lang.*;
import java.io.*;

class Binary_To_Decimal{
	public static void main (String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the binary number: ");
		String n = br.readLine();
		System.out.println(Integer.parseInt(n, 2));
		System.out.println("Press 1 perform Decimal to Binary conversion: ");
		int choice = Integer.parseInt(br.readLine());
		if (choice == 1){
			System.out.println("Enter the decimal number: ");
			int num = Integer.parseInt(br.readLine());
			System.out.println(Integer.toBinaryString(num));
		}
	}
}

Recent Posts

See All

Comments


bottom of page