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). Firstly the interview was good and I got placed in one of the top MNC.

The interview was purely 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 how to 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 convert binary integer to decimal java 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, how to convert a binary to decimal in java

Example : binary to decimal java

import java.util.Scanner;

public class BinaryToDecimal
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a Binary Number: ");

      int binaryNumber = sc.nextInt();
      int binary = binaryNumber;

      int decimal = 0;
      int toPower = 0;

      while(true)
      {
         if(binary == 0)
         {
            break;
         }
         else
         {
            int temp = binary % 10;
            decimal += temp * Math.pow(2, toPower);
            binary = binary / 10;
            toPower++;
         }
      }

      System.out.println("Binary Number = " + binary + ", Decimal Number = " + decimal);
   }
}

Output :

Please enter a Binary Number: 1000

Binary Number = 0, Decimal Number = 8


Example : binary to decimal java using Integer.parseInt() method

Here let’s see convert a binary number to decimal in java using parseint() method.

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 binaryNumber = sc.nextLine();

      System.out.println("Result : " + Integer.parseInt(binaryNumber,2));
   }
}

Output:

Please enter a Binary Number: 1000

Result: 8


conclusion

That’s it guys. This is all about convert binary number into decimal in java.

I hope you have understood converting a number from binary to decimal in java. You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

You May Also Like