Adding Two Numbers in Java

Adding two numbers is one of the first programming problems given when someone is learning a new programming language.  This program enables the programmer to focus on the language syntax since the algorithm for addition is trivial. It also demonstrates use of input/output, program structure, built-in utility libraries and basic language features like statements, comments and classes.

Java Program for Adding Two Numbers

The following program asks the user to enter two numbers separated by a space. It then outputs the sum of the numbers on the console.

// Adding two numbers in Java
import java.util.Scanner;

public class AddNumbers {
    public static void main(String[] args) {
        System.out.print("Enter two numbers separated by a space:  ");
        Scanner scanner = new Scanner(;
        int first = scanner.nextInt();
        int second = scanner.nextInt();
        int sum = first + second;
        System.out.println("Sum of "+first+" and "+second +" is "+sum);