$show=/label

Java Program to Add Two Binary Numbers

SHARE:

Example Java Program to Add Two Binary Numbers which are represented in 0 and 1 digits. How add 2 binary numbers in java.

1. Introduction


In this tutorial, You will learn a java program on how to add two binary numbers in binary format. Binary numbers are represented in only '0' and '1's. This is not having any other numbers. If a number has digits apart from 0 and 1 it is not a binary number. I have seen many examples on the internet all are showing only programs but giving the explanation. Here it is different than the Bitwise AND operator. It looks like & operator but not. You will get clarified in this article. Do not skip any content and also do not see the code directly.

Java Program to Add Two Binary Numbers


We have already discussed in previous articles on how to add two numbers in java. This is a very basic program but a common interview question. To make this complicated interviewer will ask to do not use + operator to make the sum of two numbers.



Usually this can be done in two ways. in frist way, we do not use any java API methods and just use the engineering concept from Switching theory & Logic Design (STLD) subject and in the second approach is done using Integer API.

binary number sequence addition works as follows.

Adding two binary '1's like 1 + 1 will produce digit 2 in decimal but we should convert it to binary which is 10. Here 0 is the actual sum and 1 is a carry.
0 + 0 will produce 0
0 + 1 -> 1
1 + 0 -> 1

Here all outputs are should be in binary digits and no decimal number digits are allowed.

2. Algorithm walkthrough with example: Adding Two Binay Numbers In Java


Taking two binary numbers for demonstration.

binaryNumber1 = 10101
binaryNumber2 = 10001
carry = 0

Iteration 1:


10101
10001

carry + first digit from binaryNumber1 + first digit from binaryNumber2
0 + 1 + 1 = 10 (this is a binary number) here it is combination of  carry + sum. so here carry and sum as follows.
carry = 1
first digit sum = 0

Iteration 2:


10101
10001

carry (from previous step) + second digit from binaryNumber1 + second digit from binaryNumber2
1 + 0 + 0 = 01
carry = 0
second digit sum = 1

Iteration 3:


10101
10001

carry (from previous step) + third digit from binaryNumber1 + third digit from binaryNumber2
0 + 1 + 0 = 01
carry = 0
third digit sum = 1


Iteration 4:


10101
10001

carry (from previous step) + fourth digit from binaryNumber1 + fourth digit from binaryNumber2
0 + 0 + 0 = 0
carry = 0
fourth digit sum = 0

Iteration 5:


10101
10001

carry (from previous step) + fifth digit from binaryNumber1 + fifth digit from binaryNumber2
0 + 1 + 1 = 10
carry = 1
fifth digit sum = 0


Output:


Formula: 

carry + all digts sum (fifth digit sum  fourth digit sum  third digit sum  second digit sum  first digit sum )

100110

[post_ads]

3. Example Program to add two binary numbers

The above example values are passed to this program and produce the same output.

package com.java.w3schools.blog.java.program.to;

/**
 * 
 * Program to add two binary numbers in java
 * 
 * @author venkateshn
 *
 */
public class AddBinaryNumbers {

 public static void main(String[] args) {

  // two binary numbers
  long binaryNumber1 = 10101, binaryNumber2 = 10001;

  // i represents the index of the finalSumOutput array.
  int i = 0;
  
  // carry which is to hold the value of carry.
  int carry = 0;

  // Created int array to hold the output binary number
  int[] finalSumOutput = new int[10];

  while (binaryNumber1 != 0 || binaryNumber2 != 0) {

   finalSumOutput[i++] = (int) (carry + (binaryNumber1 % 10 + binaryNumber2 % 10) % 2);

   carry = (int) ((binaryNumber1 % 10 + binaryNumber2 % 10 + carry) / 2);

   binaryNumber1 = binaryNumber1 / 10;
   binaryNumber2 = binaryNumber2 / 10;
  }
  if (carry != 0) {
   finalSumOutput[i++] = carry;
  }
  --i;
  System.out.print("Output: ");
  // printing from the last index to 0.
  while (i >= 0) {
   System.out.print(finalSumOutput[i--]);
  }
  System.out.print("\n");
 }

}

Output:

Output: 100110

Java Program to Add Two Binary Numbers- way 1

[post_ads]

4. Second Approach To Add Binary Numbers


Java API Integer class has parseInt() method which takes string and radix. If we pass radix value 2 then it considers the string values binary number. Next, we perform sum and pass the output int value to toBinaryString() method which converts integer back to binary number. We need the disired output in binary format.

Let us take a look at the below program.

package com.java.w3schools.blog.java.program.to;

/**
 * 
 * Program to add two binary numbers in java using Integer API.
 * 
 * @author venkateshn
 *
 */
public class AddBinaryNumbersWay2 {

 public static void main(String[] args) {

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

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

  // adding two integers
  Integer output = integer1 + integer2;
  
  // converting final output back to Binary Integer
  System.out.println(Integer.toBinaryString(output));

 }

}

Output:

In both approaches, the same input is taken. Observer that outputs are also same. Both are producing the results as expected.


100110

Java Program to Add Two Binary Numbers - way 2 using Integer API


5. Conclusion


In this article, You have learned how to write a java program to add two binary numbers. This can be done in two ways. The first way is without using any java API methods and use completely Switching Theory & Logic Design ( STLD ) logic. The second approach is using Integer wrapper class radix option.

Hope you enjoyed the article. Please share it with friends.

Post your questions in the comments section.

Ref

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,3,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,74,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,52,Java 8 Difference,2,java 8 Stream Examples,1,Java 9,1,Java Conversions,12,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,13,String,57,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Program to Add Two Binary Numbers
Java Program to Add Two Binary Numbers
Example Java Program to Add Two Binary Numbers which are represented in 0 and 1 digits. How add 2 binary numbers in java.
https://1.bp.blogspot.com/-WoxaaylRJn4/Xc2iMmH6sWI/AAAAAAAAB7I/1lh4Ica0Whwk8RpHbWDv0P2-DiuUUP35QCLcBGAsYHQ/s400/Java%2BProgram%2Bto%2BAdd%2BTwo%2BBinary%2BNumbers.png
https://1.bp.blogspot.com/-WoxaaylRJn4/Xc2iMmH6sWI/AAAAAAAAB7I/1lh4Ica0Whwk8RpHbWDv0P2-DiuUUP35QCLcBGAsYHQ/s72-c/Java%2BProgram%2Bto%2BAdd%2BTwo%2BBinary%2BNumbers.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/11/java-program-to-add-two-binary-numbers.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/11/java-program-to-add-two-binary-numbers.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content