Jan 2, 2022

Java Program To Add Two Binary Number - Java Program Example

Adding binary numbers in Java In this program we are using Scanner to get the input from user (user enters the two binary numbers that we need to add) and then we are adding them bit by bit using while loop and storing the result in an array.

package com.androidpro.in;

import
java.io.BufferedReader;
import
java.io.InputStreamReader;

public class
Main {

   
public static void main(String s[]) throws Exception
    {
        BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
       
System.out.print("\nEnter First Binary  Number: ");
        int
num1 = Integer.parseInt(br.readLine());
        int
num4 = num1;
       
System.out.print("\nEnter Second Binary  Number : ");
        int
num2 = Integer.parseInt(br.readLine());
        int
num5 = num2;
        int
k = 1;
        int
dec1 = 0, dec2 = 0;
        while
(num1 != 0)
        {
            dec1 = dec1 + (num1 %
10) * k;
           
k = k * 2;
           
num1 = num1 / 10;
       
}
        k =
1;
        while
(num2 != 0)
        {
            dec2 = dec2 + (num2 %
10) * k;
           
k = k * 2;
           
num2 = num2 / 10;
       
}
       
int num3 = dec1 + dec2;
       
String str1 = Integer.toBinaryString(num3);
       
System.out.print("\nAddition of Two  Number  : \n" + num4 + " + " + num5 + " = " + str1);
       
System.out.println();
   
}
}

         

When you run the program, the output will be:

Enter First Binary  Number: 01110

Enter Second Binary  Number : 111101

Addition of Two  Number  :

1110 + 111101 = 1001011

Process finished with exit code 0

Whatsapp Button works on Mobile Device only