Java Program to Add Two Numbers
Adding two numbers is one of the first programs every Java learner writes. It shows how to declare variables, use the + operator and print the result.
1. Add Two Numbers with Fixed Values
The program adds two whole numbers stored in int variables and two decimal numbers stored in double variables.
public class AddTwoNumbers {
public static void main(String[] args) {
int a = 20;
int b = 40;
int sum = a + b;
System.out.println(a + " + " + b + " = " + sum);
double x = 10.5;
double y = 20.75;
System.out.println(x + " + " + y + " = " + (x + y));
}
}
20 + 40 = 60 10.5 + 20.75 = 31.25
(x + y) matter. Without them, Java would join the text and the numbers from left to right and print 10.520.75 instead of adding them.2. Add Two Numbers with User Input
The Scanner class reads the numbers from the keyboard. nextDouble() accepts both whole and decimal numbers.
import java.util.Scanner;
public class AddTwoNumbersInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double first = scanner.nextDouble();
System.out.print("Enter second number: ");
double second = scanner.nextDouble();
scanner.close();
double sum = first + second;
System.out.println("Sum: " + sum);
}
}
Enter first number: 55.50 Enter second number: 20.40 Sum: 75.9
Decimal arithmetic in binary can show tiny rounding errors, such as 0.1 + 0.2 printing 0.30000000000000004. Use printf("%.2f", sum) to round the output, or BigDecimal for exact values.
3. Add Two Numbers Using a Method
Putting the addition in a method makes it reusable. The long version shows why the type matters: adding two large int values overflows, while long holds the correct result.
public class AddWithMethod {
static int add(int a, int b) {
return a + b;
}
static long add(long a, long b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("15 + 27 = " + add(15, 27));
int big = 2_000_000_000;
System.out.println("int: " + big + " + " + big + " = " + add(big, big));
System.out.println("long: " + big + " + " + big + " = " + add((long) big, (long) big));
}
}
15 + 27 = 42 int: 2000000000 + 2000000000 = -294967296 long: 2000000000 + 2000000000 = 4000000000
4. Summary
- Use the
+operator to add two numbers, and wrap the sum in brackets when printing it with text. - Read numbers from the user with
Scanner.nextInt()ornextDouble(). intoverflows above about 2.1 billion; uselongfor larger sums.- Use
printf()orBigDecimalwhen decimal results must look exact.