- Java Basic Programs
- Java Programming Examples
- Java Print Hello World
- Java Get Input from User
- Java Print Integer
- Java Add two Numbers
- Java Check Even or Odd
- Java Check Prime or Not
- Java Check Alphabet or Not
- Java Check Vowel or Not
- Check Reverse equal Original
- Java Fahrenheit to Celsius
- Java Celsius to Fahrenheit
- Java Perfect Number Program
- Java Find Quotient Remainder
- Java Days to Seconds
- Java Count Digits in Number
- Java Binary Number Addition
- Java Discount Program
- Java Compute Courier Charge
- Java Find Telephone Bill
- Java Print ASCII Values
- Java Check Palindrome or Not
- Java Check Armstrong or Not
- Generate Armstrong Numbers
- Add two Numbers using Pointers
- Java Mathematical Programs
- Add Subtract Multiply & Divide
- Java Make Calculator
- Java Add Digits of Number
- Java Check Leap Year or Not
- Java Check Divisibility
- Java Find Simple Interest
- Java Find Compound Interest
- Java Print Fibonacci Series
- Java Find nCr nPr
- Calculate Average & Percentage
- Java Calculate Arithmetic Mean
- Java Calculate Student Grade
- Java Print Table of Number
- Java Print Prime Numbers
- Java Add n Numbers
- Java Interchange two Numbers
- Java Reverse Numbers
- Java Swap two Numbers
- Count Positive Negative & Zero
- Find Largest of two Numbers
- Find Largest of three Numbers
- Java Find Factorial of Number
- Java Find HCF & LCM
- Area & Perimeter of Square
- Area & Perimeter of Rectangle
- Area & Circumference of Circle
- Java Conversion Programs
- Java Decimal to Binary
- Java Decimal to Octal
- Java Decimal to Hexadecimal
- Java Binary to Decimal
- Java Binary to Octal
- Java Binary to Hexadecimal
- Java Octal to Decimal
- Java Octal to Binary
- Java Octal to Hexadecimal
- Java Hexadecimal to Decimal
- Java Hexadecimal to Binary
- Java Hexadecimal to Octal
- Java Pattern Programs
- Java Pattern of Stars
- Java Pattern of Alphabets
- Java Pattern of Numbers
- Java Pyramid of Stars
- Java Pyramid of Alphabets
- Java Pyramid of Numbers
- Java Print Diamond Pattern
- Java Print Floyd Triangle
- Java Print Pascal Triangle
- Java Array Programs
- One Dimensional Array Program
- Java Linear Search
- Java Binary Search
- Find Largest Element in Array
- Find Smallest Element in Array
- Java Reverse Array
- Insert Element in Array
- Delete Element from Array
- Java Merge two Array
- Java Bubble Sort
- Java Selection Sort
- Java Insertion Sort
- Java Find Common Elements
- Java Count Even/Odd Number
- Two Dimensional Array Program
- Java Add two Matrices
- Java Subtract two Matrices
- Java Transpose Matrix
- Multiply two Matrices
- Three Dimension Array Program
- Java String Programs
- Java Print String
- Find Length of String
- Java Compare two String
- Java Copy String
- Java Concatenate String
- Java Reverse String
- Delete Vowels from String
- Delete Words from Sentence
- Find Occurrence of a Character
- Java Find Occurrence of a Word
- Occurrence of Each Character
- Java Occurrence of Each Word
- Java Count Repeated Characters
- Java Count Repeated Words
- Java Capitalize Each Word
- Java Count Vowels/Consonants
- Java Extract Numbers
- Java Count Word in String
- Remove Spaces from String
- Java Sort a String
- Java Uppercase to Lowercase
- Java Lowercase to Uppercase
- Java Swap two Strings
- Java Check Anagram or Not
- Java Check Balance Parentheses
- Java Check Password Strength
- Java File Programs
- Java Read File
- Java Write to File
- Read & Display File Content
- Java Copy File
- Java Append Text to File
- Java Merge two File
- List files in Directory
- Java Delete File
- Java Miscellaneous Programs
- Generate Random Numbers
- Java Print Time & Date
- Java Get IP Address
- Java Shutdown Computer
- Java Programming Tutorial
- Java Tutorial
Java Program to Add Two Binary Numbers
This article is created to cover some programs on addition of two binary numbers in Java. Here, I've created multiple programs on binary number addition in Java.
But before starting the program, let's first remind, how the addition of two binary number performs:
1 + 0 = 1 0 + 1 = 1 0 + 0 = 0 1 + 1 = 10 (0 and carry 1) 1 + 1 + 1 = 10 + 1 = 11 (1 and carry 1)
For example
1 1 1 0 1 + 1 1 1 1 1 ----------- 1 1 1 1 0 0
Binary Number Addition in Java using Integer
The question is, write a Java program to add two binary numbers. Both binary numbers must be entered by user at run-time. The answer to this question is given below.
The complete version of the binary number addition program in Java, is created at last of this article. But before creating the complete version of the program that performs addition on two binary numbers entered by user. Let's first create a very basic program, that provides easy-to-understand code. This program is created using int (integer) data type.
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { int binaryOne, binaryTwo, remOne, remTwo, i=0, carry=0; int[] res = new int[10]; Scanner scan = new Scanner(System.in); System.out.print("Enter the First Binary Number: "); binaryOne = scan.nextInt(); System.out.print("Enter the Second Binary Number: "); binaryTwo = scan.nextInt(); while(binaryOne!=0) { remOne = binaryOne%10; remTwo = binaryTwo%10; if(remOne==0 && remTwo==0) { if(carry==0) { res[i] = (res[i]*10) + 0; } else { res[i] = (res[i]*10) + 1; carry = 0; } } else if(remOne==0 && remTwo==1) { if(carry==0) { res[i] = (res[i]*10) + 1; } else { res[i] = (res[i]*10) + 0; carry = 1; } } else if(remOne==1 && remTwo==0) { if(carry==0) { res[i] = (res[i]*10) + 1; } else { res[i] = (res[i]*10) + 0; carry = 1; } } else if(remOne==1 && remTwo==1) { if(carry==0) { res[i] = (res[i]*10) + 0; carry = 1; } else { res[i] = (res[i]*10) + 1; carry = 1; } } else { System.out.println("\nInvalid Input!"); return; } binaryOne = binaryOne/10; binaryTwo = binaryTwo/10; i++; } if(carry==1) res[i] = (res[i]*10) + 1; System.out.print("\nResult = "); while(i>=0) { System.out.print(res[i]); i--; } } }
Here is its sample run with user input 11101 as first and 11111 as second binary number:
Above program has limitations such as what if user enters two binary numbers in which one binary number has greater or lesser number of digits than other, or what if user enters a binary number whose size is bigger than int. Therefore let's modify the above program and re-create the same program using long data type. Also this program is basically the short version of previous.
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { long binaryOne, binaryTwo; int remOne, remTwo, sumDigit, i=0, carry=0; int[] sum = new int[10]; Scanner scan = new Scanner(System.in); System.out.print("Enter the First Binary Number: "); binaryOne = scan.nextLong(); System.out.print("Enter the Second Binary Number: "); binaryTwo = scan.nextLong(); while(binaryOne!=0 || binaryTwo!=0) { remOne = (int)(binaryOne%10); remTwo = (int)(binaryTwo%10); sumDigit = remOne + remTwo + carry; sum[i] = (int)(sumDigit%2); carry = (int)(sumDigit/2); binaryOne = binaryOne/10; binaryTwo = binaryTwo/10; i++; } if(carry==1) sum[i] = carry; System.out.print("\nResult = "); while(i>=0) { System.out.print(sum[i]); i--; } } }
Here is its sample run with user input 1010 as first and 111111 as second binary number:
Let's again shorten the above program. Here is the short version of the above program. The i++ is the post increment of i, that means the current value of i gets used, and then incremented its value by 1:
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { long binaryOne, binaryTwo; int remOne, remTwo, sumDigit, i=0, carry=0; int[] sum = new int[10]; Scanner scan = new Scanner(System.in); System.out.print("Enter Two Binary Numbers: "); binaryOne = scan.nextLong(); binaryTwo = scan.nextLong(); while(binaryOne!=0 || binaryTwo!=0) { sum[i++] = (int)((binaryOne%10 + binaryTwo%10 + carry)%2); carry = (int)((binaryOne%10 + binaryTwo%10 + carry)/2); binaryOne /= 10; binaryTwo /= 10; } if(carry==1) sum[i] = carry; System.out.print("\nResult = "); while(i>=0) System.out.print(sum[i--]); } }
Still the program is not perfect, because I've used array whose limit is 10. I know you can increase the limit by 100 or more. But what about the data type long, whose limit is 9,223,372,036,854,775,807.
Therefore, I must recommend you to go with string type to add any two binary numbers, without depending on its size or the number of digits, given binary numbers have.
Binary Number Addition in Java using String
Before creating the complete version, let's first create a simple and basic version using string. This program assumes that the input of two binary numbers from user at run-time is of same number of digits:
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { String binaryOne, binaryTwo, resRev="", resOrig=""; char charOne, charTwo, carry='0'; int i; Scanner scan = new Scanner(System.in); System.out.print("Enter Two Binary Numbers: "); binaryOne = scan.next(); binaryTwo = scan.next(); for(i=(binaryOne.length()-1); i>=0; i--) { charOne = binaryOne.charAt(i); charTwo = binaryTwo.charAt(i); if(charOne=='0' && charTwo=='0') { if(carry=='0') resRev = resRev + "0"; else { resRev = resRev + "1"; carry = '0'; } } else if(charOne=='0' && charTwo=='1') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='0') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='1') { if(carry=='0') { resRev = resRev + "0"; carry = '1'; } else { resRev = resRev + "1"; carry = '1'; } } else { System.out.println("\nInvalid Input!"); return; } } if(carry=='1') resRev = resRev + "1"; for(i=(resRev.length()-1); i>=0; i--) resOrig = resOrig + resRev.charAt(i); System.out.println("\nResult = " + resOrig); } }
Here is its sample run with user input 11101 and 11111 as two binary numbers:
Binary Number Addition in Java - Complete Version
Now let's create the complete version of the binary number addition program in Java. I'm saying this program as the complete version, because this program handles all types of errors, also handles binary numbers having any number of digits.
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { String binaryOne, binaryTwo, resRev="", resOrig=""; char charOne, charTwo, carry='0'; int binaryOneLen, binaryTwoLen, i, j, len; Scanner scan = new Scanner(System.in); System.out.print("Enter the First Binary Number: "); binaryOne = scan.next(); System.out.print("Enter the Second Binary Number: "); binaryTwo = scan.next(); binaryOneLen = binaryOne.length(); binaryTwoLen = binaryTwo.length(); if(binaryOneLen > binaryTwoLen) { for(i=(binaryOneLen-1), j=(binaryTwoLen-1); j>=0; i--, j--) { charOne = binaryOne.charAt(i); charTwo = binaryTwo.charAt(j); if(charOne=='0' && charTwo=='0') { if(carry=='0') resRev = resRev + "0"; else { resRev = resRev + "1"; carry = '0'; } } else if(charOne=='0' && charTwo=='1') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='0') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='1') { if(carry=='0') { resRev = resRev + "0"; carry = '1'; } else { resRev = resRev + "1"; carry = '1'; } } else { System.out.println("\nInvalid Input!"); return; } } for(i=i; i>=0; i--) { charOne = binaryOne.charAt(i); if(carry=='1') { if(charOne=='1') { resRev = resRev + "0"; carry = '1'; } else if(charOne=='0') { resRev = resRev + "1"; carry = '0'; } else { System.out.println("\nInvalid Input!"); return; } } else { resRev = resRev + charOne; } } } else if(binaryOneLen < binaryTwoLen) { for(i=(binaryOneLen-1), j=(binaryTwoLen-1); i>=0; i--, j--) { charOne = binaryOne.charAt(i); charTwo = binaryTwo.charAt(j); if(charOne=='0' && charTwo=='0') { if(carry=='0') resRev = resRev + "0"; else { resRev = resRev + "1"; carry = '0'; } } else if(charOne=='0' && charTwo=='1') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='0') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='1') { if(carry=='0') { resRev = resRev + "0"; carry = '1'; } else { resRev = resRev + "1"; carry = '1'; } } else { System.out.println("\nInvalid Input!"); return; } } for(i=j; i>=0; i--) { charTwo = binaryTwo.charAt(i); if(carry=='1') { if(charTwo=='1') { resRev = resRev + "0"; carry = '1'; } else if(charTwo=='0') { resRev = resRev + "1"; carry = '0'; } else { System.out.println("\nInvalid Input!"); return; } } else { resRev = resRev + charTwo; } } } else { for(i=(binaryOneLen-1); i>=0; i--) { charOne = binaryOne.charAt(i); charTwo = binaryTwo.charAt(i); if(charOne=='0' && charTwo=='0') { if(carry=='0') resRev = resRev + "0"; else resRev = resRev + "1"; } else if(charOne=='0' && charTwo=='1') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='0') { if(carry=='0') resRev = resRev + "1"; else { resRev = resRev + "0"; carry = '1'; } } else if(charOne=='1' && charTwo=='1') { if(carry=='0') { resRev = resRev + "0"; carry = '1'; } else { resRev = resRev + "1"; carry = '1'; } } else { System.out.println("\nInvalid Input!"); return; } } } if(carry=='1') resRev = resRev + "1"; len = resRev.length(); for(i=len-1; i>=0; i--) resOrig = resOrig + resRev.charAt(i); System.out.println("\nResult = " + resOrig); } }
Here is its sample run with user input 1010110101011 as first and 11110001101111101 as second number:
I know the program is little longer, but I recommend you to take a deep concentrate on the program, to understand the logic used in the program. There are many other ways too, to create the same program. Since the article is getting longer than usual, therefore I'm letting you to do modify the program and create another way with yourself.
« Previous Program Next Program »