Addition Operation Using Bitwise Operators In Java

Today we will be discussing addition operation using bitwise operators in java.

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 dig in

example: Addition Operation Using Bitwise Operators In Java

Addition Operation Using Bitwise Operators In Java

Also Read – Binary Search Program Java

//  Using Scanner class in package java.util
import java.util.Scanner;

public class Bitwise_Addition {

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

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *