Java Programs›Basics & I/O›Add Two Numbers

Add Two Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Adding two numbers together with the + operator is one of the most basic arithmetic operations in Java.

Given two integers, add them and print the result.

Input
5, 3
Output
Sum: 8

Java Program

Java
public class AddTwoNumbers { public static void main(String[] args) { int a = 5; int b = 3; int sum = a + b; // numeric addition System.out.println("Sum: " + sum); } }

Output

Sum: 8

Core Logic

The + operator between two int values adds them directly, and the result can be stored in a third variable before printing.

How It Works
  1. 1Two int variables, a and b, hold the numbers to add.
  2. 2a + b evaluates to their sum, which is stored in sum.
  3. 3System.out.println concatenates the label "Sum: " with the numeric value using +.
With a = 5 and b = 3, a + b evaluates to 8, so the program prints "Sum: 8".
💡

Key Point: Java's + operator does either numeric addition or string concatenation depending on the operand types — mixing an int with a String (like here) triggers concatenation, not addition.

Key Concepts

+ operatorintarithmetic

Approach 2: Java 8

Java
import java.util.function.IntBinaryOperator; public class AddTwoNumbersLambda { public static void main(String[] args) { int a = 5; int b = 3; // The addition logic itself is stored as a lambda, not written inline IntBinaryOperator add = (x, y) -> x + y; int sum = add.applyAsInt(a, b); System.out.println("Sum: " + sum); } }

Output

Sum: 8

Core Logic

The + operation itself can be captured as a value — an IntBinaryOperator lambda — instead of being written inline.

How It Works
  1. 1IntBinaryOperator add = (x, y) -> x + y; stores the addition logic in a variable, using a functional interface built into java.util.function.
  2. 2add.applyAsInt(a, b) invokes the lambda with a and b, running the same + operation the direct version wrote inline.
  3. 3The result is printed exactly as before.
With a = 5 and b = 3, add.applyAsInt(5, 3) evaluates the lambda body x + y and returns 8.
💡

Key Point: Wrapping + in an IntBinaryOperator is overkill for a single addition, but the same shape scales well once the operation itself needs to be passed around or swapped out — like choosing between add, subtract, and multiply at runtime.

Key Concepts

IntBinaryOperatorfunctional interfacelambda expression

Interview Questions

What happens if the sum is larger than an int can hold?

It overflows and wraps around to a negative number without any error. Use long for large values, or Math.addExact(a, b), which throws an ArithmeticException on overflow.

What does "Sum: " + a + b print?

The concatenation runs left to right, so with a = 5 and b = 3 it prints "Sum: 53". Wrap the addition in parentheses, "Sum: " + (a + b), to print 8.

Learn the Concept

Related Programs