Java Program For Binary Addition

By | 2018-08-04T02:44:42+05:30 June 23rd, 2016|java programs|1 Comment

Here we are going to write a Java program for Binary Addition. As part of the implementation of Binary Addition, we will also check whether a number is binary or not.

Java Binary Addition :

Addition_Binary_Numbers.java

package com.onlinetutorialspoint.patterns;

import java.util.Scanner;

public class Addition_Binary_Numbers {

    public static void main(String args[]) {
        long binary1, binary2;
        int i = 0, remainder = 0;
        int[] sum = new int[30];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter any binary number : ");
        binary1 = sc.nextLong();
        System.out.print("Enter another binary number : ");
        binary2 = sc.nextLong();
        if (isBinary(binary1) && isBinary(binary2)) {
            while (binary1 != 0 || binary2 != 0) {
                sum[i++] = (int) ((binary1 % 10 + binary2 % 10 + remainder) % 2);
                remainder = (int) ((binary1 % 10 + binary2 % 10 + remainder) / 2);
                binary1 = binary1 / 10;
                binary2 = binary2 / 10;
            }
            if (remainder != 0) {
                sum[i++] = remainder;
            }
            --i;
            System.out.print("Sum of two binary numbers : ");
            while (i >= 0) {
                System.out.print(sum[i--]);
            }
        } else {
            System.out.println("Please enter valid binary number..");
        }
        
    }

    public static boolean isBinary(long number) {
        while (number != 0) {
            if (number % 10 > 1) {
                return false;
            }
            number = number / 10;
        }
        return true;
    }

}

Output :

javac Addition_Binary_Numbers.java
>java Addition_Binary_Numbers

Enter any binary number : 1011011
Enter another binary number : 1110111
Sum of two binary numbers : 11010010

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

One Comment

  1. rostislavkaleta@gmail.com'
    Rostislav Kaleta May 28, 2018 at 1:27 pm - Reply

    “here is the code you want” No how it works, no why, when its good to choose this, its downsides.No explanation why sum integer array has predefined 30 spaces.

Leave A Comment