00:00

Java Program to Add Two Binary Numbers

Last updated:

Binary numbers use only two digits, 0 and 1. Adding them works like decimal addition: you add one column at a time from right to left and carry to the next column. This page shows three ways to add two binary numbers in Java: digit by digit with numbers, digit by digit with strings read from the user, and with Java's built-in conversion methods.

1. Rules of Binary Addition

Each column adds two bits plus any carry from the previous column. The result bit is the total modulo 2 (total % 2), and the carry is the total divided by 2 (total / 2).

Bit 1Bit 2Carry inResult bitCarry out
00000
01010
10010
11001
11111

For example, 10101 (21) + 10001 (17) = 100110 (38).

2. Add Binary Numbers Stored as long

Here the binary numbers are written as ordinary long values made of 0s and 1s. The loop takes the last digit of each number with % 10, adds them with the carry, and then removes that digit with / 10. The result bits are collected in a StringBuilder and reversed at the end.

AddBinaryNumbers.java
public class AddBinaryNumbers {
    public static void main(String[] args) {
        long binary1 = 10101;
        long binary2 = 10001;

        System.out.println("First binary number: " + binary1);
        System.out.println("Second binary number: " + binary2);

        StringBuilder sum = new StringBuilder();
        int carry = 0;

        while (binary1 != 0 || binary2 != 0 || carry != 0) {
            int bit1 = (int) (binary1 % 10);   // last digit of the first number
            int bit2 = (int) (binary2 % 10);   // last digit of the second number

            int total = bit1 + bit2 + carry;
            sum.append(total % 2);             // result bit
            carry = total / 2;                 // carry for the next column

            binary1 /= 10;
            binary2 /= 10;
        }

        if (sum.length() == 0) {
            sum.append(0);                     // both numbers were 0
        }

        System.out.println("Sum of the binary numbers: " + sum.reverse());
    }
}
Output
First binary number: 10101
Second binary number: 10001
Sum of the binary numbers: 100110
Note: a long holds at most 19 digits, so this approach only works for binary numbers up to 19 bits. For longer numbers, use strings as in the next example.

3. Add Binary Strings Entered by the User

Reading the numbers as String values removes the length limit. The addBinary() method walks both strings from the last character to the first. charAt(i) - '0' turns the character '0' or '1' into the number 0 or 1. The input is checked with a regular expression so that only 0s and 1s are accepted.

AddBinaryStrings.java
import java.util.Scanner;

public class AddBinaryStrings {

    static String addBinary(String a, String b) {
        StringBuilder sum = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;

        while (i >= 0 || j >= 0 || carry != 0) {
            int total = carry;
            if (i >= 0) total += a.charAt(i--) - '0';
            if (j >= 0) total += b.charAt(j--) - '0';

            sum.append(total % 2);
            carry = total / 2;
        }
        return sum.reverse().toString();
    }

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

        System.out.print("Enter first binary number: ");
        String first = scanner.next();
        System.out.print("Enter second binary number: ");
        String second = scanner.next();
        scanner.close();

        if (!first.matches("[01]+") || !second.matches("[01]+")) {
            System.out.println("Please enter only 0s and 1s.");
            return;
        }

        System.out.println("Sum: " + addBinary(first, second));
    }
}
Output (with sample input)
Enter first binary number: 1101
Enter second binary number: 111
Sum: 10100

4. Add Binary Numbers Using Built-in Methods

Java can convert between binary and decimal for you. Integer.parseInt(text, 2) reads a binary string as an int, and Integer.toBinaryString() turns the sum back into binary. This is the shortest solution, but it is limited to the range of int (31 bits for positive values). Use Long for up to 63 bits, or new BigInteger(text, 2) for any length.

AddBinaryBuiltIn.java
public class AddBinaryBuiltIn {
    public static void main(String[] args) {
        String binary1 = "1011";
        String binary2 = "111";

        int number1 = Integer.parseInt(binary1, 2);   // 11
        int number2 = Integer.parseInt(binary2, 2);   // 7

        int sum = number1 + number2;                  // 18

        System.out.println(binary1 + " + " + binary2 + " = " + Integer.toBinaryString(sum));
        System.out.println("In decimal: " + number1 + " + " + number2 + " = " + sum);
    }
}
Output
1011 + 111 = 10010
In decimal: 11 + 7 = 18

5. Summary

  • Add binary numbers column by column from right to left: the result bit is total % 2 and the carry is total / 2.
  • Keep looping while either number has digits left or a carry remains, so the final carry is not lost.
  • Use strings for binary numbers of any length; long values are limited to 19 digits.
  • Integer.parseInt(s, 2) and Integer.toBinaryString() give a short solution for small numbers.

Related Programs