Convert Binary to Decimal in Java
Problem
Each bit in a binary number is worth a power of two that doubles from right to left, so 110101 means 32 + 16 + 4 + 1 = 53.
Given a string containing a binary number, print its decimal value.
Java Program
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "110101";
int decimal = 0;
for (char bit : binary.toCharArray()) {
decimal = decimal * 2 + (bit - '0'); // shift what we have left by one place, then add the new bit
}
System.out.println("Decimal of " + binary + ": " + decimal);
}
}Output
Core Logic
Reading the bits left to right, doubling the running total before adding each new bit gives every earlier bit its correct power of two without computing any powers.
- 1
decimalstarts at 0. - 2For each character,
bit - '0'turns'0'or'1'into the number 0 or 1. - 3
decimal * 2shifts the value built so far one binary place to the left. - 4Adding the new bit fills the place that just opened up.
110101: 1 → 3 → 6 → 13 → 26 → 53, doubling and adding one bit at a time.Key Point: This doubling trick (Horner's method) avoids Math.pow entirely, and the same loop converts from any base — swap 2 for 8 or 16.
Why: Each of the n characters is processed once, using a single running total.
Key Concepts
Approach 2: Using Integer.parseInt() with Radix 2
public class BinaryToDecimalBuiltIn {
public static void main(String[] args) {
String binary = "110101";
int decimal = Integer.parseInt(binary, 2); // radix 2 tells parseInt the digits are bits
System.out.println("Decimal of " + binary + ": " + decimal);
}
}
Output
Core Logic
Integer.parseInt accepts a second argument, the radix, which tells it which base the digits are written in.
- 1
Integer.parseInt(binary, 2)reads the string as base 2. - 2Any character other than 0 or 1 makes it throw a
NumberFormatException. - 3Strings longer than 31 bits overflow an
int;Long.parseLong(s, 2)handles up to 63.
Integer.parseInt("110101", 2) returns 53.Key Point: The built-in validates the input for you, which the manual loop above does not — it would happily treat '2' as a bit.
Why: The parser walks the string once, keeping only the running value.
Key Concepts
Interview Questions
How do you convert a binary string longer than 31 bits?
Use Long.parseLong(s, 2) for up to 63 bits, or new BigInteger(s, 2) for any length.
What happens with characters other than 0 and 1?
Integer.parseInt(s, 2) throws NumberFormatException; a manual loop should validate each character itself.