In this example, we have shared how to add two binary numbers using Java. Copy the following Java program and execute it to see the output. We have shared the real time program output at the end of this page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /** * Add two Binary numbers in Java. */ 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"); } } |
Program Output
1 2 3 | Enter first binary number: 11100 Enter second binary number: 10101 Output: 110001 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.