;

Java Program to Add Two Binary Numbers


Tutorialsrack 19/04/2021 Java

In this java program, you will learn how to add two binary numbers and Print the output on the screen in Java. The binary number system has only two symbols 0 & 1, so a binary number consists of only 0’s and 1’s. Here we are using two approaches to perform the addition of two binary numbers.

Approach 1: Java Program to Add Two Binary Numbers

In this approach, we do not use any java API methods and we just use the engineering concept from the Switching Theory & Logic Design (STLD) subject. 

Approach 1: Java Program to Add Two Binary Numbers
//Java Program to Add Two Binary Numbers

import java.util.Scanner;

public class JavaPrograms {

	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: 110011

Enter second binary number: 111011

Output: 1101110

Approach 2: Java Program to Add Two Binary Numbers

In this approach, the Java API Integer class has a parseInt() method which takes two parameters: string and radix. If we pass radix value 2 then it considers the string values as binary numbers. Next, we perform sum and pass the output integer value to toBinaryString() method which converts the integer back to binary number. And this is our desired output in binary format.

Approach 2: Java Program to Add Two Binary Numbers
//Java Program to Add Two Binary Numbers

public class JavaPrograms {

	public static void main(String[] args) {

		// Two binary numbers in string format
		String binaryNumber1 = "10101", binaryNumber2 = "10001";

		// converting strings into binary format numbers
		int integer1 = Integer.parseInt(binaryNumber1, 2);
		int integer2 = Integer.parseInt(binaryNumber2, 2);

		// adding two integers
		Integer output = integer1 + integer2;

		// converting final output back to Binary Integer
		System.out.println("Output: " + Integer.toBinaryString(output));

	}
}
Output

Output: 100110


Related Posts



Comments

Recent Posts
Tags