• Famous interview java question on conversions . 
  • We can convert binary to decimal in two ways
    1.Using Integer.parseInt() method
    2.Using custom logic



1.Write a Java Program to convert binary to decimal number in java without using Integer.parseInt() method.

  1. import java.util.Scanner;
  2. public class DecimalFromBinary {
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  System.out.println("Enter a binary number: ");
  12.  
  13.   int  binarynum =in.nextInt();
  14.   int binary=binarynum;
  15.         
  16. int decimal = 0;
  17. int power = 0;
  18.  
  19. while(true){
  20.  
  21.  if(binary == 0){
  22.  
  23.         break;
  24.  
  25.  } else {
  26.  
  27.    int tmp = binary%10;
  28.    decimal += tmp*Math.pow(2, power);
  29.    binary = binary/10;
  30.    power++;
  31.  
  32.  }
  33. }
  34.         System.out.println("Binary="+binary+" Decimal="+decimal); ;
  35. }
  36.  
  37. }

Output:


  1. Enter a binary number: 
  2. 101
  3. Binary=101 Decimal=5




2.Write a Java Program to convert binary to decimal number in java using Integer.parseInt() method.



  1. import java.util.Scanner;
  2. public class ConvertBinaryToDecimal{
  3.  
  4.     /**
  5.      *www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.  Scanner in = new Scanner( System.in );
  11.  
  12.  System.out.println("Enter a binary number: ");
  13.  String binaryString =input.nextLine();
  14.  
  15.  System.out.println("Result: "+Integer.parseInt(binaryString,2));

  16.  
  17. }
  18.  
  19. }


Output:


  1. Enter a binary number:
  2. 001
  3. Result: 1

java program to convert binary to decimal


You Might like:

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

2 comments for Java Example Program to convert binary to decimal

Select Menu