Program to Convert Binary to Decimal in Java

Here you will get program to convert binary to decimal in Java.

There are mainly two ways to convert a binary number to decimal number in Java.

1. By using parseInt() method of Integer class.
2. By using user defined logic.

Program to Convert Binary to Decimal in Java

By using Integer.parseInt()

Integer.parseInt() method takes two arguments. First argument is a string and second argument is the base or radix in which we have to convert the number. The output is the integer represented by the string argument in the specified radix. Below is the program for it.

 

 

Without using Integer.parseInt()

In this method we have to define our own logic for converting binary number to decimal. The approach that we will use here is mentioned in below example.

binary to decimal example

Image Source

The program that implements above approach is mentioned below.

 

 

Output

Program to Convert Binary to Decimal in Java
If you found anything missing or incorrect in above programs then please mention it by commenting below.

4 thoughts on “Program to Convert Binary to Decimal in Java

  1. Bismeet Singh

    import java.util.Scanner;
    public class Binary2Decimal{
    public static void main(String[] args) {
    Scanner no=new Scanner(System.in);
    System.out.println(“Enter a binary number”);
    String n=no.nextLine();
    System.out.println(Integer.parseInt(n, 2));
    }
    }
    Exception in thread “main” java.lang.NumberFormatException: For input string: “2”
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at binary2decimal.Binary2Decimal.main(Binary2Decimal.java:8)

    Reply
    1. Admin Post author

      You have to enter binary number, here you have entered decimal number 2 so exception is coming.

      Reply
  2. Ab niazi

    public class Bin2dec {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println(“Enter the Word”);
    String str = s.next();
    int number;
    double digit = 0 , result = 0;
    int check = 1;
    for(int i = 0; i < str.length() ; i++){
    if(str.charAt(i) =='1' || str.charAt(i) =='0'){
    check = 1;
    }
    else{
    check = 0;
    }
    }
    if(check == 0){
    System.out.println("Error: Invalid Binary String \"" + str + "\"");
    }
    else if(check == 1){
    number = Integer.parseInt(str);
    for(int i = 0; i < str.length() ; i++){
    digit = number % 10;
    number = number / 10;
    result = result + (digit * pow(2,i));
    }
    System.out.println((int)result);
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *