Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Add Two numbers Without using Arithmetic Operator

  • Last Updated : 12 Apr, 2021

Here, we need to write a function that returns the sum of two stated integers. And the function must not utilize any of the arithmetic operators such as +, ++, –, -, .. Etc.). It will be a very basic elementary level program to compute the sum by simply using the ‘+’ operator and thereby simply printing and displaying out the resultant. But if we refrain from constraint not to use any of arithmetic operator then there is only one way out that is with the use of XOR operator which can perform an addition operation for two given bits. And for the carry bit, we can use AND (&) operator.

It is done using the bit-wise operators. Here we are going to use mainly three operations as follows:

  1. Bit-wise XOR
  2. Bit-wise AND
  3. Bit-wise left shift operator 

First, the numbers are converted in binary format. Considering 8 indices for an integer data type.  Now the carry is handled by a bit-wise left shift operator and the rest of the binary is displayed on the screen as an integer number depicting the sum of the above two integers. It is depicted below: 

Input  : 1, 2
Output : 3
a = 1 : 00000001
b = 2 : 00000010
----------------
c = 3 : 00000011 

Implementation:

Example

Java




// Java Program to find the Sum of Two Numbers
// Without Using any Arithmetic Operator
  
// Importing input output classes 
import java.io.*;
  
// Main class
class GFG {
  
    // Method to sum two integer elements
    static int Sum(int a, int b)
    {
  
        // Iterating until there is no carry
        while (b != 0) {
  
            // Using AND operator
            int carry = a & b;
  
            // Using XOR operator
            a = a ^ b;
  
            // Shifting the carry by one so that
            // adding it to the integer 'a'
            // gives the desired output
            b = carry << 1;
        }
        return a;
    }
  
    // Method 2
    // Main driver method
    public static void main(String arg[])
    {
  
        // Print the sum of custom integer numbers to be
        // summed up passed as an argunts
        System.out.println(Sum(2, 3));
    }
}
Output
5

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :