Java Program to Perform Addition Operation Using Bitwise Operators

This is the java program to perform addition of two numbers without using any arithmetic operators. The summation of two numbers can be obtained using XOR operation and carry can be obtained using AND performed at bit level.

Here is the source code of the Java Program to Perform Addition Operation Using Bit-wise Operators. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

//This is sample program to perform addition operation using bitwise operators.
import java.util.Scanner;
 
public class Bitwise_Addition 
{
    static int add(int x, int y)
    {
        int carry;
        while(y!=0)
        {
            carry = x & y;
            x = x ^ y;
            y = carry << 1;
        }
        return x;
    }
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the numbers to be added:");
        int x = input.nextInt();
        int y = input.nextInt();
        System.out.println("The Summation is: "+add(x, y));
        input.close();
    }
}

Output:

$ javac Bitwise_Addition.java
$ java Bitwise_Addition
 
Enter the numbers to be added:
15
16
The Summation is: 31

Related posts:

Đồng bộ hóa các luồng trong Java
Java Program to Perform Left Rotation on a Binary Search Tree
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Hướng dẫn Java Design Pattern – Bridge
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Java Program to Implement Regular Falsi Algorithm
Guide to CountDownLatch in Java
Lập trình mạng với java
Case-Insensitive String Matching in Java
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Implement ConcurrentSkipListMap API
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Hướng dẫn Java Design Pattern – Builder
Java Program to Implement ArrayDeque API
Sending Emails with Java
JPA/Hibernate Persistence Context
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Java Program to Implement Stack
Java Program to Implement Shoelace Algorithm
Truyền giá trị và tham chiếu trong java
Getting Started with Custom Deserialization in Jackson
Java Program to Describe the Representation of Graph using Adjacency List
Send an email with an attachment
Spring Data – CrudRepository save() Method
Guide to Apache Commons CircularFifoQueue
HTTP Authentification and CGI/Servlet
Generate Spring Boot REST Client with Swagger
Java Program to Implement Interpolation Search Algorithm
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Cơ chế Upcasting và Downcasting trong java
Logging in Spring Boot