w3resource
Java Programming Exercies

Java Exercises: Convert a binary number to decimal number

Java Basic: Exercise-22 with Solution

Write a Java program to convert a binary number to decimal number.

Binary number: A binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).

Decimal number: The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is also called base-ten positional numeral system.

Pictorial Presentation: Binary to Decimal number

Java: Convert a binary number to decimal number

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise22 {
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  long binaryNumber, decimalNumber = 0, j = 1, remainder;
  System.out.print("Input a binary number: ");
  binaryNumber = sc.nextLong();

  while (binaryNumber != 0) 
  {
   remainder = binaryNumber % 10;
   decimalNumber = decimalNumber + remainder * j;
   j = j * 2;
   binaryNumber = binaryNumber / 10;
  }
  System.out.println("Decimal Number: " + decimalNumber);
 }
}

Sample Output:

Input a binary number: 100                                                                                    
Decimal Number: 4 

Flowchart:

Flowchart: Java exercises: Convert a binary number to decimal number

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to convert a decimal number to octal number.
Next: Write a Java program to convert a binary number to hexadecimal number.

What is the difficulty level of this exercise?