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:
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 5, b = 10;
System.out.println("Sum = "+(a+b));
}
}
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.
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
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
public class Main {
public static void main(String[] args) {
int a = 15;
int b = 25;
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
System.out.println("Sum = " + a);
}
}
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.
import java.io.*;
class GFG {
public static void main (String[] args) {
int a= Integer.parseInt(args[0]);
int b= Integer.parseInt(args[1]);
System.out.println("Sum:"+(a+b));
}
}
Output

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.
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
BigInteger sum;
String input1 = "9482423949832423492342323546";
String input2 = "6484464684864864864864876543";
BigInteger a = new BigInteger(input1);
BigInteger b = new BigInteger(input2);
sum = a.add(b);
System.out.println("Sum of Two BigIntegers: "+ sum);
}
}
Output
Sum of Two BigIntegers: 15966888634697288357207200089
Explanation: String values are converted into BigInteger objects and added using the add() method to avoid overflow.