2 Ways to Add Binary Numbers in Java - Coding Example

In the last article, I have shown you how to subtract binary numbers in Java, and today, you will learn the opposite i.e. how to add binary numbers in Java. You can do binary addition in Java either by writing your own logic or by taking advantage of the Java API, which allows you to convert a binary string into a binary number. Though, if you want you can also use the logic I have shared in my earlier post about how to check binary numbers to verify input before converting it to a binary number. In this article, we'll take a look at both methods of adding two binary numbers in Java. In this article, I have given you two solutions to add binary numbers in Java.

In the first solution, we have used the Java API, which first converts the given binary String to a decimal number using the Integer.parseInt() method, which is also used to convert String to Integer.

This method is overloaded to convert String to an integer in several other number systems e.b. binary, octal, decimal, and hexadecimal.

The overloaded version takes another int parameter radix, which you can use to convert a binary String to a decimal integer like Integer.parseInt(number, 2), where the number is a String denoting a binary number. For example, String "101" will be converted into integer 5 and "1000" will be converted into 8.

Once you have got the number in decimal format, you can just add those numbers and convert the result to the binary String by using Integer.toBinaryString(sum);. 

That's all is needed if you use Java API as the first convert binary String to decimal numbers, add them and then convert the result back to binary form.

The second solution is a bit complex because we are actually doing the binary addition with binary numbers i.e. we are adding numbers from the right and then carrying the carry towards the left. It's how you do in the paper. You can further check these free data structure and algorithms courses to learn more bout coding essentials like data structure, binary system, etc. 



Java Program to add two binary numbers? Examples

Here is our complete solution of adding two binary numbers in Java. You can run this Java program into your favorite Java IDE like Eclipse or NetBeans or IntelliJIDEA, or even from a command prompt to add two given binary numbers. 
import java.util.Scanner;

/*
 * Java Program to add two binary numbers.
 * You can either write your own method or you 
 * can use Java API for doing binary addition.
 * 
 * input: 1010 + 101
 * output = 1111
 */

public class Main {

  public static void main(String[] args) {

    System.out.println("Welcome to Java program to add two binary numbers");
    Scanner scnr = new Scanner(System.in);

    System.out.println("Please enter first binary number");
    String first = scnr.nextLine();

    System.out.println("Please enter second binary number");
    String second = scnr.nextLine();

    String addition = add(first, second);
    System.out.println("addition of two binary number is : " + addition);

    String sum = sum(first, second);
    System.out.println("Sum of two binary number is : " + sum);

    scnr.close();

  }

  /**
   * Java method to calculate sum of two binary numbers this method calculate
   * sum by first converting binary String to binary numbers and then adding
   * them using binary arithmetic.
   * 
   * @param first
   * @param second
   * @return sum of two given binary numbers
   */
  public static String add(String first, String second) {
    int b1 = Integer.parseInt(first, 2);
    int b2 = Integer.parseInt(second, 2);
    int sum = b1 + b2;
    return Integer.toBinaryString(sum);
  }

  /**
   * Java method to add two binary numbers. This method doesn't use Java API,
   * instead develop it's own logic to perform binary addition.
   * 
   * @param bin1
   * @param bin2
   * @return addition of two binary numbers
   */
  public static String sum(String b1, String b2) {
    int len1 = b1.length();
    int len2 = b2.length();
    int carry = 0;
    String res = "";
    // the final length of the result depends on the bigger length between b1
    // and b,
    // (also the value of carry, if carry = 1, add "1" at the head of result,
    // otherwise)
    int maxLen = Math.max(len1, len2);
    for (int i = 0; i < maxLen; i++) {

      // start from last char of String b1 and b2
      // notice that left side is an int and right side is char
      // so we need to minus the decimal value of '0'
      int p = i < len1 ? b1.charAt(len1 - 1 - i) - '0' : 0;
      int q = i < len2 ? b2.charAt(len2 - 1 - i) - '0' : 0;
      int tmp = p + q + carry;
      carry = tmp / 2;
      res = tmp % 2 + res;
    }
    return (carry == 0) ? res : "1" + res;
  }

}

Output
Welcome to Java program to add two binary numbers
Please enter first binary number
1010
Please enter second binary number
11
addition of two binary number is : 1101
Sum of two binary number is : 1101


If you are not sure how this program works, consider debugging this Java program by the instructions given in this article. When you debug the code inside the first method you can clearly see that Integer. parseInt(number, 2) converts a binary number into a decimal integer.

Coding - 2 Ways to Add Binary Numbers in Java



That's all about how to write a Java program to add two binary numbers. You can use any of the methods to perform binary addition, but if you are asked in interviews, you should first use the Java way by using Integer.toString() method and then write your logic to calculate the sum of two binary numbers, if and only if Interviewer asked you to do so.


Further Learning
How to do the binary search in Java?
10 Algorithm books Every Programmer Should Read
How to implement Quicksort algorithm in Java?
5 Free Courses to learn Data Structure and Algorithms

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

Lastly, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one?  Do let me know in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.