Java Tutorial
🔍
Java ProgramsBasics & I/OAdd 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

Related Programs