Binary To Decimal Java

Hey guys!! Welcome to flower brackets blog. Today you are here to learn binary to decimal java.

binary to decimal java

This is my experience in interview (Java Interview). The interview was good and I got placed in one of the top MNC. The interview was based on JAVA.

Also Read – Bubble Sort Java Program

After initial rounds including technical interview there was a system test in which I got a program on write a program to convert binary to decimal number in java without using Integer.parseInt() method and to find the area of circle.

(Update : Scroll down to learn java program to convert binary to decimal using Integer.parseInt() method)

Though the latter was easy to write as well as to execute. You can find the area of circle program here.

Lets dig into former program that is, program to convert binary to decimal in java

Example : 

// without using any predefined methods
import java.util.Scanner;

public class BinaryToDecimalExample 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a binary number : ");
      int num = sc.nextInt();

      int decimal = 0, temp = 0; 
      while(num != 0)
      {
         decimal += ((num % 10) * Math.pow(2, temp));
         num = num / 10;
         temp++;
      } 
      System.out.println(decimal);
      sc.close();
   }
}

Output :

Please enter a binary number : 1000

8


Java program to convert binary to decimal using parseint() method

Here let’s see Integer.parseint() method to convert binary to decimal in java. This method takes two arguments. One is string and another is radix to which we have to convert the number.

Also Read – Area of Rectangle Program in Java

import java.util.Scanner;

public class BinaryToDecimalDemo
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner( System.in);
      System.out.println("Please enter a binary number : ");
      String num = sc.nextLine();
      System.out.println("Result : " + Integer.parseInt(num, 2));
      sc.close();
   }
}

Output:

Please enter a binary number: 1000

Result: 8


Conclusion

That’s it guys. This is all about java program for binary to decimal conversion. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Related Posts