Home » Java Program » Java Program to add two numbers without addition operator

Java Program to add two numbers without addition operator

Support this post with a reaction:

6,271 views

In this tutorial you will learn writing program to add two numbers without using addition operator in Java.

Read This:  Write a program in C to add two number without using third variable.

How this Java program will behave?

This program will take two number as a Input. And After performing some operation as per program, it will return addition.

Suppose if we give input 35 and 20. Our program will return 55 as an output without using of an addition operator.

Below is a program to add two numbers without using + operator in Java

import java.util.Scanner;
public class Main {
     public static void main(String[] arg) 
	 {
	   int x, y ;
	   Scanner sc = new Scanner(System.in);	
	   System.out.print("Please Give first number: ");
	   x = sc.nextInt(); 
	   System.out.print("Please Give second number: ");
	   y = sc.nextInt(); 
      while(y != 0){
            int temp = x & y;
            x = x ^ y;
            y = temp << 1;
        }
        System.out.print("Sum = "+x); 
	}	
} 

Output:

Please Give first number: 6
Please Give second number: 8
Sum = 14

Conclusion

The above Java program takes two integers as input and calculates their sum without using the + operator. It uses the XOR (^) operator to add the numbers without considering carry bits and the AND (&) operator to identify the carry bits. The carry is shifted left using << 1 and added repeatedly until there is no carry left. Finally, when y becomes 0, x contains the resulting sum, which is printed as the output.