VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-add-two-numbers/

⇱ Java Program to Add Two Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Add Two Numbers

Last Updated : 21 Jan, 2026

In Java, adding numbers is a basic operation that can be performed in multiple ways depending on the use case, such as direct arithmetic, bit manipulation, loops, command-line arguments, or handling very large numbers.

Example:


Output
Sum = 15

Explanation: here we are adding two integers using '+' operator;

Below are some of the approaches to perform addition.

1. Add Two Numbers Using Arithmetic Operator

The most straightforward way to add two numbers in Java is by using the + operator.


Output
Sum = 30

Explanation: The + operator performs arithmetic addition of the two integer values.

2. Add Two Numbers Using Bit Manipulation

Addition can also be done without using the + operator by applying bitwise operations.

  • XOR (^) performs addition without carry
  • AND (&) combined with left shift (<<) calculates the carry
  • The process continues until the carry becomes zero

Output
Sum = 40

Explanation: XOR calculates the sum bits, AND with left shift calculates carry bits, and the loop continues until no carry remains.

3. Add Two Numbers Using Command Line Arguments

Java allows passing input values at runtime using command-line arguments.

Output

👁 Adding_Two_Numbers_Using_Command_Line

Explanation: The arguments are converted from String to int using Integer.parseInt() and then added.

4. Add Two Large Numbers Using BigInteger

When numbers exceed the range of int or long, Java provides the BigInteger class.


Output
Sum of Two BigIntegers: 15966888634697288357207200089

Explanation: String values are converted into BigInteger objects and added using the add() method to avoid overflow.

Comment
Article Tags:
Article Tags: