How to Convert Binary to Decimal in Java (4 Methods)

Introduction

Converting a binary (base-2) number back to its decimal (base-10) equivalent is the natural companion to decimal-to-binary conversion.

Unlike decimal-to-binary conversion, which repeatedly divides by 2, binary-to-decimal conversion is based on positional notation. Once you understand how positional values work, converting binary numbers becomes a straightforward process of multiplying each digit by its corresponding power of 2 and summing the results.

This guide covers:

Advertisement
  • Converting a binary number stored as an integer
  • Converting a binary number stored as a string
  • A recursive implementation
  • Java's built-in Integer.parseInt() method with a radix argument

By the end, you'll understand both the manual algorithm and the production-ready approach.


What Is Binary-to-Decimal Conversion?

Our everyday number system is decimal (base 10).

Each digit represents a power of 10.

For example:

 
234
 

means:

 
2 × 100 + 3 × 10 + 4 × 1
 

or

 
2 × 10² + 3 × 10¹ + 4 × 10⁰
 

Binary works exactly the same way, except the base is 2.

Consider the binary number:

 
1101
 

Its positional values are:

Binary Digit Power of 2 Decimal Value
1 8
1 4
0 0
1 2⁰ 1

Adding these values:

 
8 + 4 + 0 + 1 = 13
 

Therefore:

 
1101₂ = 13₁₀
 

Binary-to-decimal conversion simply performs this positional-value calculation programmatically.


Method 1: Using a While Loop with Integer Input

Many beginner programming exercises represent the binary number as an integer.

For example:

 
1101
 

is stored as:

 
int binary = 1101;
 

Although this isn't how binary data is represented internally by computers, it is a common interview format.

The algorithm repeatedly:

  1. Extracts the last digit.
  2. Multiplies it by the current power of 2.
  3. Adds the result to the running decimal value.
  4. Doubles the power of 2.
  5. Removes the last digit.

Java Program

 
public class BinaryToDecimalIntInput {

    public static void main(String[] args) {

        int binary = 1101;

        int decimal = 0;

        int base = 1;

        while (binary != 0) {

            int lastDigit = binary % 10;

            decimal = decimal + lastDigit * base;

            base = base * 2;

            binary = binary / 10;
        }

        System.out.println("Decimal value: " + decimal);
    }
}
 

Output

 
Decimal value: 13
 

Step-by-Step Execution

Suppose the input is:

 
1101
 

Iteration 1

Current binary value:

 
1101
 

Extract last digit:

 
1101 % 10 = 1
 

Current power:

 
1
 

Update decimal:

 
0 + (1 × 1) = 1
 

Double the base:

 
2
 

Remove last digit:

 
110
 

Iteration 2

Current binary value:

 
110
 

Last digit:

 
0
 

Update:

 
1 + (0 × 2) = 1
 

Base becomes:

 
4
 

Remaining number:

 
11
 

Iteration 3

Current binary value:

 
11
 

Last digit:

 
1
 

Update:

 
1 + (1 × 4) = 5
 

Base becomes:

 
8
 

Remaining number:

 
1
 

Iteration 4

Current binary value:

 
1
 

Last digit:

 
1
 

Update:

 
5 + (1 × 8) = 13
 

Remaining number:

 
0
 

The loop terminates.

Final answer:

 
13
 

Why Does the base Variable Double?

Initially:

 
base = 1
 

which represents:

 
2⁰
 

After every digit:

 
base = base * 2;
 

The values become:

 
1

2

4

8

16

32
 

These are exactly the positional values used in binary numbers.

Time Complexity

  • Time Complexity: O(d)
  • Space Complexity: O(1)

where d is the number of binary digits.


Method 2: Converting a Binary String Input

In real applications, binary values are usually represented as strings, not integers.

This approach is more flexible because:

  • Leading zeros are preserved.
  • Very long binary values are easier to handle.
  • Input validation becomes simpler.

Java Program

 
public class BinaryToDecimalStringInput {

    public static void main(String[] args) {

        String binary = "1101";

        int decimal = 0;

        int base = 1;

        for (int i = binary.length() - 1; i >= 0; i--) {

            char digitChar = binary.charAt(i);

            int digit = digitChar - '0';

            decimal += digit * base;

            base *= 2;
        }

        System.out.println("Decimal value: " + decimal);
    }
}
 

Output

 
Decimal value: 13
 

How It Works

Unlike the previous solution, we don't extract digits using % 10.

Instead, we process each character in the string.

Starting from the last character:

 
1101
   ↑
 

The loop moves from right to left because the rightmost digit represents:

 
2⁰
 

The next digit represents:

 
 

followed by:

 
 

and so on.

Why Does digitChar - '0' Work?

Suppose the character is:

 
'1'
 

Internally, Java stores characters using Unicode values.

The characters:

 
'0'
'1'
'2'
...
'9'
 

appear in consecutive order.

Therefore:

 
'1' - '0'
 

evaluates to:

 
1
 

Similarly,

 
'0' - '0'
 

becomes:

 
0
 

This is the standard Java technique for converting a numeric character into its integer value.

Time Complexity

  • Time Complexity: O(d)
  • Space Complexity: O(1)

where d is the number of binary digits.

Method 3: Using Recursion

The binary-to-decimal conversion can also be implemented using recursion.

Instead of processing every digit inside a loop, each recursive call processes one binary digit and then delegates the remaining work to the next recursive call.

Java Program

 
public class BinaryToDecimalRecursion {

    static int convert(String binary, int index) {

        if (index == binary.length()) {
            return 0;
        }

        int digit = binary.charAt(index) - '0';

        int power = binary.length() - index - 1;

        return (int) (digit * Math.pow(2, power))
                + convert(binary, index + 1);
    }

    public static void main(String[] args) {

        String binary = "1101";

        System.out.println("Decimal value: " + convert(binary, 0));
    }
}
 

Output

 
Decimal value: 13
 

How It Works

Suppose the binary number is:

 
1101
 

The recursive calls occur like this:

 
convert("1101", 0)
 

Processes:

 
1 × 2³ = 8
 

 
convert("1101", 1)
 

Processes:

 
1 × 2² = 4
 

 
convert("1101", 2)
 

Processes:

 
0 × 2¹ = 0
 

 
convert("1101", 3)
 

Processes:

 
1 × 2⁰ = 1
 

 
convert("1101", 4)
 

The base case:

 
if (index == binary.length())
 

returns:

 
0
 

Now the recursive calls return:

 
1 + 0
 

 
0 + 1
 

 
4 + 1
 

 
8 + 5
 

Final result:

 
13
 

Why Is the Power Calculated This Way?

The expression:

 
binary.length() - index - 1
 

calculates how far the current digit is from the rightmost position.

For:

 
1101
 
Index Digit Power
0 1 3
1 1 2
2 0 1
3 1 0

These powers correspond exactly to:

 
2³

2²

2¹

2⁰
 

Time Complexity

  • Time Complexity: O(d)
  • Space Complexity: O(d)

where d is the number of binary digits.


Method 4: Using Java's Built-In Integer.parseInt()

For real-world applications, Java already provides a built-in solution.

The method:

 
Integer.parseInt()
 

accepts a second argument called the radix, which specifies the base of the input number.

Java Program

 
public class BinaryToDecimalBuiltIn {

    public static void main(String[] args) {

        String binary = "1101";

        int decimal = Integer.parseInt(binary, 2);

        System.out.println("Decimal value: " + decimal);
    }
}
 

Output

 
Decimal value: 13
 

Why Does the Second Argument Matter?

Consider:

 
Integer.parseInt("1101");
 

Java assumes base 10.

The result becomes:

 
1101
 

which is incorrect for binary conversion.

Instead, write:

 
Integer.parseInt(binary, 2);
 

The second argument tells Java:

Interpret this string using base 2.

Now:

 
1101₂
 

correctly becomes:

 
13₁₀
 

Time Complexity

  • Time Complexity: O(d)
  • Space Complexity: O(1)

Comparing Binary-to-Decimal and Decimal-to-Binary

These two conversions are opposite processes.

Decimal to Binary

Starts with:

 
13
 

The algorithm repeatedly:

  • Divides by 2
  • Collects remainders
  • Stops when the quotient becomes 0

This is essentially a breaking down process.


Binary to Decimal

Starts with:

 
1101
 

The algorithm:

  • Multiplies each digit by its positional value.
  • Adds all the values together.

This is a building up process.


Quick Comparison

Decimal → Binary Binary → Decimal
Divide by 2 Multiply by powers of 2
Collect remainders Sum positional values
Build binary representation Build decimal value
Breaking down Building up

Understanding both algorithms together provides a complete understanding of binary number conversion.


How Java Handles This Internally (Memory Concept)

Methods 1 and 2

The variables:

  • binary
  • decimal
  • base
  • digit

are primitive values stored in the JVM stack.

In Method 2, the String object itself is stored on the heap, while the local variable holds only a reference to it.

The loop reads characters using:

 
charAt()
 

without modifying the original string.


Method 3

Every recursive call creates a new stack frame.

Each frame stores:

  • binary
  • index
  • digit
  • power

The recursive calls continue until the base case is reached.

As the stack unwinds, each call contributes its positional value to the final decimal result.


Method 4

Internally,

 
Integer.parseInt(binary, 2)
 

performs an optimized parsing algorithm.

Conceptually, it follows the same positional-notation principle as the manual implementation but hides the complexity behind a single method call.


Real-Life Analogy: Reading Toggle Switches

Imagine four switches arranged from left to right.

Each switch has a fixed value:

Switch Value
1 8
2 4
3 2
4 1

Suppose the switches are:

 
ON

ON

OFF

ON
 

Their values become:

 
8

4

0

1
 

Adding them together:

 
8 + 4 + 0 + 1 = 13
 

This is exactly how binary-to-decimal conversion works.

Each binary digit either contributes its positional value (if it is 1) or contributes nothing (if it is 0).

Comparison of All Methods

Method Input Format Time Complexity Space Complexity Best Used When
While Loop (Integer Input) Binary stored as an int O(d) O(1) Common beginner exercises and interviews
String Processing Binary stored as a String O(d) O(1) General-purpose manual conversion
Recursion Binary stored as a String O(d) O(d) Learning recursion and recursive problem-solving
Integer.parseInt() Binary stored as a String O(d) O(1) Production code and real-world applications

Note: Here, d represents the number of binary digits.


Best Practices

  • Use Integer.parseInt(binaryString, 2) in production code. It is concise, reliable, and thoroughly tested.
  • Prefer storing binary numbers as strings rather than integers. Strings preserve leading zeros and better represent binary data.
  • Understand positional notation instead of simply memorizing the algorithm. The same concept applies to binary, octal, hexadecimal, and every other positional number system.
  • Validate binary input before conversion. Ensure the string contains only:

     
    0
     

    and

     
    1
     

    to avoid invalid input or NumberFormatException.

  • If very large binary values must be processed, use long or BigInteger instead of int to avoid overflow.
  • Test your implementation using different types of input, including:
    • Zero
    • Leading zeros
    • Single-bit values
    • Invalid binary strings

Common Mistakes Beginners Make

1. Forgetting the Radix Argument

Many beginners write:

 
Integer.parseInt(binary);
 

Instead of:

 
Integer.parseInt(binary, 2);
 

Without the second argument, Java assumes the number is decimal.

For example:

 
"1101"
 

becomes:

 
1101
 

instead of:

 
13
 

2. Processing the Binary Digits in the Wrong Direction

The rightmost binary digit always represents:

 
2⁰
 

Each position moving left doubles the positional value.

Processing the digits from left to right without correctly calculating their powers often produces incorrect results.


3. Confusing Binary-to-Decimal with Decimal-to-Binary

These algorithms are opposites.

Binary → Decimal

  • Multiply by powers of 2.
  • Add the values.

Decimal → Binary

  • Divide by 2.
  • Record remainders.

Using the wrong algorithm leads to incorrect answers.


4. Not Validating Input

Strings such as:

 
110201
 

or

 
10A1
 

are not valid binary numbers.

Always verify that every character is either:

 
0
 

or

 
1
 

before performing the conversion.


5. Using char - '0' Without Understanding It

The expression:

 
digit = binary.charAt(i) - '0';
 

works because the numeric characters '0' through '9' have consecutive Unicode values.

Understanding why it works makes the code much easier to remember and apply correctly.


Expert Tips for Interviews

A strong interview answer might sound like this:

"Binary-to-decimal conversion is based on positional notation. Each binary digit represents a power of 2 depending on its position, starting with 2⁰ at the rightmost digit. I process the binary digits, multiply each digit by its positional value, and accumulate the result. In production code, I'd simply use Integer.parseInt(binaryString, 2), but it's important to understand the manual positional-value algorithm because the same concept applies to every positional number system."

Explaining why positional notation works demonstrates a deeper understanding than simply describing the multiplication steps.


Pros and Cons

While Loop (Integer Input)

Pros

  • ✅ Easy to understand
  • ✅ Common interview format
  • ✅ Demonstrates digit extraction

Cons

  • ❌ Artificial input representation
  • ❌ Cannot preserve leading zeros
  • ❌ Less realistic than string input

String Processing

Pros

  • ✅ Flexible
  • ✅ Preserves leading zeros
  • ✅ Matches real-world binary input

Cons

  • ❌ Slightly longer implementation than the built-in method

Recursion

Pros

  • ✅ Demonstrates recursive thinking
  • ✅ Elegant implementation
  • ✅ Useful for recursion practice

Cons

  • ❌ Uses additional stack space
  • ❌ Slightly slower than the iterative approach due to recursive calls
  • ❌ Uses Math.pow() for each digit

Using Integer.parseInt()

Pros

  • ✅ Short and readable
  • ✅ Highly optimized
  • ✅ Standard production solution
  • ✅ Handles radix conversion automatically

Cons

  • ❌ Doesn't teach the underlying positional-notation algorithm
  • ❌ May not be allowed in interview questions that prohibit built-in methods

Frequently Asked Questions

1. What is the easiest way to convert binary to decimal in Java?

Use:

 
Integer.parseInt(binaryString, 2);
 

The second argument specifies that the input should be interpreted as a binary number.


2. What happens if I omit the radix argument?

Java assumes base 10.

For example:

 
Integer.parseInt("1101");
 

returns:

 
1101
 

instead of:

 
13
 

3. Why does binary-to-decimal conversion use powers of 2?

Binary is a base-2 number system.

Each position represents the next higher power of 2:

 
1

2

4

8

16

32
 

4. Can I convert binary to decimal without built-in methods?

Yes.

Simply process every binary digit, multiply it by its positional value, and add the results.


5. Why is the binary number processed from right to left?

The rightmost digit represents:

 
2⁰
 

Each position moving left doubles the positional value.

Processing from right to left makes assigning powers straightforward.


6. Can I solve this problem using recursion?

Yes.

Each recursive call processes one binary digit and returns its positional contribution plus the result of the remaining recursive calls.


7. What is the time complexity?

Every binary digit is processed exactly once.

Therefore:

  • Time Complexity: O(d)

where d is the number of binary digits.


8. What does char - '0' do?

It converts a numeric character into its integer value.

For example:

 
'1' - '0'
 

becomes:

1

Similarly

'0' - '0'

becomes:

0

9. Can this algorithm convert hexadecimal to decimal?

Yes.

The positional-notation principle is exactly the same.

Only the base changes:

  • Binary → Base 2
  • Octal → Base 8
  • Decimal → Base 10
  • Hexadecimal → Base 16

10. Is binary-to-decimal conversion a common interview question?

Yes.

It is frequently paired with decimal-to-binary conversion to test a candidate's understanding of number systems and positional notation.


11. Does Integer.parseInt() work for very large binary numbers?

Only within the range of Java's int.

For larger values, use:

Long.parseLong(binaryString, 2);

or

new BigInteger(binaryString, 2);

12. Which approach should I use in real projects?

Use:

Integer.parseInt(binaryString, 2);

It is concise, efficient, and easier to maintain than manual implementations.