How to Add two Binary Numbers in Java Program ?

  Java Interview Q&A

Hello readers In this tutorial, we will read a Java program to add two binary numbers. A binary number system has only two symbols 0 and 1, so a binary number has only 0 and 1. Before we write a program in addition to this, let us see how we add on paper, it is shown in the picture below:

Adding binary numbers in Java

Adding binary numbers in Java

Adding binary numbers in Java

In this program we are using a scanner to get input from the user (the user enters the two binary numbers we need to add) and then we are adding them a bit using a loop and the result. Let us store in an array.

import java.util.Scanner;
public class JavaExample {
   public static void main(String[] args)
   {
	//Two variables to hold two input binary numbers	 
	long b1, b2;
	int i = 0, carry = 0;

	//This is to hold the output binary number
	int[] sum = new int[10];

	//To read the input binary numbers entered by user
	Scanner scanner = new Scanner(System.in);

	//getting first binary number from user
	System.out.print("Enter first binary number: ");
	b1 = scanner.nextLong();
	//getting second binary number from user
	System.out.print("Enter second binary number: ");
	b2 = scanner.nextLong();

	//closing scanner after use to avoid memory leak
	scanner.close();
	while (b1 != 0 || b2 != 0) 
	{
		sum[i++] = (int)((b1 % 10 + b2 % 10 + carry) % 2);
		carry = (int)((b1 % 10 + b2 % 10 + carry) / 2);
		b1 = b1 / 10;
		b2 = b2 / 10;
	}
	if (carry != 0) {
		sum[i++] = carry;
	}
	--i;
	System.out.print("Output: ");
	while (i >= 0) {
		System.out.print(sum[i--]);
	}
	System.out.print("\n");  
   }
}

Output:

Enter first binary number: 11100
Enter second binary number: 10101
Output: 110001

 

LEAVE A COMMENT