Binary to Decimal Conversion in Java — Definition, Examples and Program

Learn how to convert a binary number to decimal in Java with clear explanation, step-by-step examples, and a simple program.

Binary to Decimal Conversion in Java — Definition, Examples and Program

A binary number is a number in base 2, containing only 0s and 1s. Converting a binary number to decimal (base 10) is essential in computer programming and digital systems.

How to Convert Binary to Decimal?

  1. Take the binary number as input.
  2. Start from the rightmost digit (least significant bit).
  3. Multiply each bit by 2 raised to its position index (starting from 0).
  4. Sum all these values to get the decimal equivalent.

Example 1

Binary Number: 1101

Decimal: 13

Example 2

Binary Number: 10101

Decimal: 21

Java Program for Binary to Decimal Conversion


import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a binary number: ");
        String binary = sc.next();

        int decimal = 0;
        int length = binary.length();

        for (int i = 0; i < length; i++) {
            char bit = binary.charAt(length - 1 - i); // Start from rightmost bit
            if (bit == '1') {
                decimal += Math.pow(2, i);
            }
        }

        System.out.println("Decimal of " + binary + " is " + decimal);
    }
}

Sample Output


Enter a binary number: 1101
Decimal of 1101 is 13

Enter a binary number: 10101
Decimal of 10101 is 21

Practice Challenges

  1. Write a program to convert multiple binary numbers entered by the user into decimal.
  2. Modify the program to validate input (only 0s and 1s allowed).
  3. Write a program to convert binary to octal and hexadecimal without using built-in functions.

Binary to decimal conversion is a key concept in computer science and helps understand the working of digital systems. This Java program allows beginners to convert binary numbers step by step easily.