Bitwise Addition

Sharing is healthy !!

Hello everyone!! Welcome to flower brackets blog. Today we will be discussing bitwise addition.

Basically bitwise operators allow us to manipulate bit values for comparisons in calculation.

Bitwise operators use similar symbols to boolean operators. First we have (&) ampersand which is “AND” and we have pipe ( | ) which is “OR”, we have the carrot (^) which is “XOR” and the tilde (~) which is NOT.

Bitwise addition is common question in java interview. So, let’s see an example on how to add two numbers without using arithmetic operators in java.

example: Bitwise Addition

Bitwise Addition

Also Read – Binary Search Program Java

//  Using Scanner class in package java.util

import java.util.Scanner;

public class BitwiseAddition
{
   static int add(int a,int b)
   {
      int carry;  // declare integer carry variable

      while(b!=0)
      {
         carry = a & b;
         a = a ^ b;
         b = carry << 1;
      }
      return a;
   }

   // The main() method starts here

   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      // scanner which can parse primitive types and strings using regular expressions.

      System.out.println("Please enter numbers to be added: ");

      int a = sc.nextInt();  // Scans the next token of the input as an int

      int b = sc.nextInt();  // Scans the next token of the input as an int

      System.out.println("The output is: " + add(a,b));
      sc.close();  // Closes this scanner

   }
}

Output:

Please enter numbers to be added: 5 5
The output is: 10


conclusion

That’s it guys. This is all about add two numbers without using + operator. I hope you have understood bitwise addition.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this article if you like.

Sharing is healthy !!