Program to add two binary numbers in java (example)

  • Given two binary numbers in java
  • We would like to find out sum of two binary numbers.

Examples: add two binary numbers in java

Example 1 : 
Enter first binary number :  100
Enter second binary number : 010
                         ----------
Sum of binary numbers :      110

Example 2: 
Enter first binary number  : 111
Enter second binary number : 101
                         -----------
Sum of binary numbers :     1000

Algorithm to add two binary numbers in java:

  1. User enter the two binary string in console
  2. Convert first binary string to decimal using Integer.parseInt method
  3. Convert second binary string to decimal using Integer.parseInt method.
  4. Add two decimal numbers using + operator.
  5. Finally, convert the decimal number to binary using Integer.toBinaryString method.

Methods of Integer class to convert binary to/from integer:

Method Name Description
int parseInt(String s, int radix) Parses the string argument as a signed integer in the radix specified by the second argument.
String toBinaryString(int i) Returns a string representation of the integer argument as an unsigned integer in base 2.

Program: add two binary string numbers in java

package org.learn.beginner;

import java.util.Scanner;

public class AddBinaryNumbers {

    public static String add(String num1, String num2) {

        //convert binary string to decimal number
        int num1Binary = Integer.parseInt(num1, 2);

        //convert binary string to decimal number
        int num2Binary = Integer.parseInt(num2, 2);

        //Add two decimal numbers
        int sumOfNumbers = num1Binary + num2Binary;

        //convert decimal to binary and return back
        return Integer.toBinaryString(sumOfNumbers);
    }

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

            //111
            System.out.print("Enter first binary number : ");
            String number1 = scanner.next();
            //101
            System.out.print("Enter second binary number : ");
            String number2 = scanner.next();

            /*
                    111
                  + 101
              ---------------
                   1100
              ---------------
            */
            System.out.println("Sum of numbers :" + add(number1,number2));
        }
    }
}

Output: sum of two binary string numbers in java

Enter first binary number : 100
Enter second binary number : 010
Sum of numbers :110
************************************************

Enter first binary number : 111
Enter second binary number : 101
Sum of numbers :1100
Scroll to Top