Adding two integers is the “Hello, World” of arithmetic in Java — but a truly useful beginner guide goes far beyond a single line of code. In this post you will learn five distinct ways to add two integers in Java: hardcoded literals, Scanner console input, command-line arguments, method parameters, and streams. Along the way you will understand integer overflow, the difference between int and long, and how to guard against bad input.
Method 1 — Adding Hardcoded Integers
public class AddTwoIntegers {
public static void main(String[] args) {
int a = 15;
int b = 27;
int sum = a + b;
System.out.println(a + " + " + b + " = " + sum);
}
}
15 + 27 = 42
Method 2 — Reading Input with Scanner
The most common pattern for beginners: prompt the user, read two numbers, and print their sum.
import java.util.Scanner;
public class AddWithScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first integer : ");
int a = scanner.nextInt();
System.out.print("Enter second integer: ");
int b = scanner.nextInt();
int sum = a + b;
System.out.println("Sum = " + sum);
scanner.close();
}
}
Enter first integer : 100
Enter second integer: 250
Sum = 350
Method 3 — Command-Line Arguments
Useful for scripting: pass the two numbers when launching the program.
public class AddFromArgs {
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Usage: java AddFromArgs <num1> <num2>");
System.exit(1);
}
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println(a + " + " + b + " = " + sum);
} catch (NumberFormatException e) {
System.err.println("Error: both arguments must be integers.");
System.exit(1);
}
}
}
java AddFromArgs 123 456
# 123 + 456 = 579
Method 4 — Reusable add() Method
Encapsulating addition in a dedicated method is the right approach whenever the logic appears more than once or needs to be unit-tested.
public class MathUtils {
/** Returns the sum of two int values. */
public static int add(int a, int b) {
return a + b;
}
/** Returns the sum of two long values (safe for large numbers). */
public static long addLong(long a, long b) {
return a + b;
}
/** Adds two ints safely; throws ArithmeticException on overflow. */
public static int addExact(int a, int b) {
return Math.addExact(a, b); // throws if result overflows int
}
public static void main(String[] args) {
System.out.println(add(10, 32)); // 42
System.out.println(addLong(2_000_000_000L,
2_000_000_000L)); // 4000000000
try {
System.out.println(addExact(Integer.MAX_VALUE, 1)); // throws!
} catch (ArithmeticException e) {
System.out.println("Overflow detected: " + e.getMessage());
}
}
}
42
4000000000
Overflow detected: integer overflow
Method 5 — Sum a List with Java Streams
import java.util.List;
public class StreamSum {
public static void main(String[] args) {
List<Integer> numbers = List.of(10, 20, 30, 40, 50);
// Sum all elements using IntStream
int total = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of list: " + total); // 150
// Sum just two specific elements
int pairSum = List.of(7, 11).stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Pair sum: " + pairSum); // 18
}
}
Understanding Integer Overflow
Java’s int is a signed 32-bit type. Its range is −2,147,483,648 to 2,147,483,647. Adding beyond that limit wraps around silently:
int max = Integer.MAX_VALUE; // 2,147,483,647
int next = max + 1; // wraps to -2,147,483,648 (no exception!)
System.out.println(next); // -2147483648
// Safe alternatives:
long safe = (long) max + 1; // promote to long first
int checked = Math.addExact(max, 1); // ArithmeticException on overflow
int vs long: When to Use Which
| Type | Size | Range | Use When |
|---|---|---|---|
int | 32 bits | −2.1B to 2.1B | Typical counts, indices, ages |
long | 64 bits | −9.2 quintillion to 9.2Q | Timestamps, file sizes, financial totals |
BigInteger | Arbitrary | Unlimited | Cryptography, factorial of large N |
JUnit Test for the add() Method
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MathUtilsTest {
@Test void addPositives() { assertEquals(42, MathUtils.add(10, 32)); }
@Test void addNegatives() { assertEquals(-5, MathUtils.add(-3, -2)); }
@Test void addMixed() { assertEquals(0, MathUtils.add(-7, 7)); }
@Test void addZero() { assertEquals(9, MathUtils.add( 9, 0)); }
@Test void overflowThrows() {
assertThrows(ArithmeticException.class,
() -> MathUtils.addExact(Integer.MAX_VALUE, 1));
}
}
See Also
- Java Streams API: The Complete Reference Guide
- Java Comparable vs Comparator
- Java BufferedReader Tutorial
- Disarium Number in Java
Conclusion
Adding two integers in Java can be as simple as a + b, but a solid understanding of the operator also means knowing when to use long to avoid overflow, how to detect overflow with Math.addExact(), and how to structure the operation as a reusable, testable method. The five approaches shown here cover every real-world scenario: interactive programs, command-line tools, library utilities, and stream pipelines.