Java Program to Add Two Numbers

Introduction

In this tutorial, we will learn how to write a simple Java program to add two numbers. We will explore three different approaches to perform the addition:

  1. Using the Addition Operator (+): The fundamental way to perform addition in Java.
  2. Using Local Variable Type Inference (var): A modern syntax approach introduced in Java 10.
  3. Using a Helper Method: A modular approach that separates addition logic into a reusable method.

Note: The var keyword simplifies variable declarations, but the underlying addition operation remains identical. Meanwhile, the method-based approach demonstrates how the addition logic can be separated into a reusable method.

Let’s explore each approach step by step.

Add Two Numbers in Java Using the Addition (+) Operator

Problem Statement

Write a Java program to store two integer values in two variables using the addition operator (+), calculate their sum, and display the result on the console.

The program should use predefined integer values and should not use the Scanner class or any user input.

Prerequisite Knowledge

  • Basic Java Syntax: Understanding the basic structure of a Java program, including a class and the main() method.
  • Variables and Data Types: Knowing how to declare variables using the int data type and assign integer values to them.
  • Arithmetic Operators: Understanding how the addition operator (+) is used to add two integer values.
  • Console Output: Knowing how to use System.out.println() to display text and calculated values on the console.

Learning Objectives

After completing this program, you will be able to:

  1. Declare integer variables using the int data type and assign values to them.
  2. Use the addition operator (+) to calculate the sum of two integer values.
  3. Store and use calculated results in a Java variable.
  4. Display the calculated sum using System.out.println().
  5. Write and execute a simple Java program using predefined values without taking input from the user.

Input Format and Output Format

  • No external user input.
  • Two integer values assigned directly to variables within the main method.
  • Print the calculated integer sum directly to the standard output.

Expected Solution Approach of the Program

  1. Create a variable for the first number.
  2. Create a variable for the second number.
  3. Use the + operator to add them.
  4. Store the result in a third variable.
  5. Print the result.

The main operation is:

int sum = firstNumber + secondNumber;

Complete Java Program to Add Two Numbers

public class AddTwoNumbers {
    public static void main(String[] args) {
        // Declare and initialize the two integer numbers
        int firstNumber = 15;
        int secondNumber = 25;

        // Calculate the sum using the addition operator (+)
        int sum = firstNumber + secondNumber;

        // Display the formatted result
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Sum           : " + sum);
    }
}

Expected Output:

First Number  : 15
Second Number : 25
-------------------------
Sum           : 40

Step-by-Step Code Explanation

Step 1: Program Entry Point

public class AddTwoNumbers {
public static void main(String[] args) {
  • public class AddTwoNumbers: Declares a class named AddTwoNumbers that contains the program’s code.
  • public static void main(String[] args): Defines the main() method, which is the entry point of the Java application. The Java runtime starts program execution by calling this method.

Step 2: Declare and Initialize Variables

// Declare and initialize the two integer variables
int firstNumber = 15;
int secondNumber = 25;

  • int: Specifies the data type that the variables can store integer values. In Java, int is a 32-bit signed integer type.
  • firstNumber = 15;: Declares the variable firstNumber and initializes it with the integer value 15.
  • secondNumber = 25;: Declares the variable secondNumber and initializes it with the integer value 25.

After declaration and initialization, we will perform addition and display the result.

Step 3: Perform Addition and Store the Result

// Calculate the sum using the addition operator (+)
int sum = firstNumber + secondNumber;
  • firstNumber + secondNumber: The + operator adds the stored values (15 + 25), producing 40.
  • int sum = ...: Creates a third integer variable named sum and stores the resulting value (40) inside it.

Step 4: Display Formatted Output

// Display the formatted result on the console
System.out.println("First Number : " + firstNumber);
System.out.println("Second Number : " + secondNumber);
System.out.println("-------------------------");
System.out.println("Sum : " + sum);
  • System.out.println(): Prints the specified text or value to the console and then moves the cursor to the next line.
  • String concatenation (+): Combines a string with another value to produce a single string for output. Here, labels such as “Sum : ” are combined with the numeric values stored in the variables.

Java Addition Program Using Local Variable Type Inference (var)

In Java 10 and later, you can use var for local variable type inference to make variable declarations more concise. When you use var, the Java compiler infers the type of each local variable from its initializer. In this program, firstNumber, secondNumber, and sum are inferred as int because their initializers produce int values.

public class Main {
    public static void main(String[] args) {
        // Declare and initialize the two integer numbers using 'var'
        var firstNumber = 15;
        var secondNumber = 25;

        // Calculate the sum using the addition operator (+)
        var sum = firstNumber + secondNumber;

        // Display the formatted result
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Sum           : " + sum);
    }
}

Standard Method-Based Approach (Modular)

Separating the addition logic into a separate reusable method is a common modular programming approach. It can improve code organization and make the logic reusable when the same operation is needed in multiple places. Let’s write a Java program to add two numbers using a separate reusable method approach.

public class Main {
    public static void main(String[] args) {
        int firstNumber = 15;
        int secondNumber = 25;

        int sum = add(firstNumber, secondNumber);

        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Sum           : " + sum);
    }

    // Helper method to perform addition
    public static int add(int a, int b) {
        return a + b;
    }
}

Expected Output:

First Number  : 15
Second Number : 25
-------------------------
Sum           : 40

In this example code:

  • add(firstNumber, secondNumber) calls the add() method and passes the values 15 and 25 as arguments.
  • public static int add(int a, int b) declares a method named add that accepts two int parameters and returns an int.
  • return a + b; adds the two parameters and returns the resulting value.
  • int sum = add(firstNumber, secondNumber); stores the returned value (40) in the sum variable.

Follow-up Challenge

Challenge 1: Change Values

Modify the program by changing the values of the two integer variables:

int firstNumber = 50;
int secondNumber = 75;

Task:

Before running the program, predict the output produced by the addition operation.

Expected Output:

125

Challenge: Can you correctly predict the result without executing the program?

Challenge 2: Add Three Integers

Modify the program to work with three integer values instead of two. Use the addition operator (+) to calculate and display their total.

Example Input:

10
20
30

Expected Output:

60

Challenge: Update the program so that it correctly adds all three integers and displays the total.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.