View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Java Program to Add Two Numbers

Updated on 25/06/202512,309 Views

A Java program to add two numbers is one of the first exercises every Java programmer encounters, and for good reason. It builds the foundation for understanding how variables, operators, and input/output work together in Java.

In this tutorial, we'll explore multiple ways to perform addition, including taking user input, using command line arguments, and defining custom methods. We’ll also go a step further and cover how to add three or even N numbers.

Let’s get started with clean, efficient code to master addition in Java.

Method 1: Java Program to Add Two Numbers (Using + Operator)

The simplest method to find out the sum of numbers in Java is by using the "+" operator. This method involves directly adding the two numbers and storing the result in a variable. Let's look at an example to illustrate this:

public class SumExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;

int sum = num1 + num2; // using + operator to add

System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}

Output:

The sum of 10 and 20 is: 30

Explanation:

Two variables have been declared and initialized in the aforementioned program. The console stores and shows the sum of the numbers.

Real-life scenario:

Imagine you are building a shopping cart application, and you need to calculate the total price of two items selected by a customer. You can use the "Sum of Two Numbers" method to add the prices of the selected items and display the total to the customer.

Method 2: Java Program to Add Two Numbers Using Scanner (User Input)

In many scenarios, we need to add numbers that are provided by the user at runtime. Java provides the `Scanner` class, which allows us to take user input. Let's see how we can use this method to add two numbers:

import java.util.Scanner;


public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter the first number: ");
        int num1 = input.nextInt();
        
        System.out.print("Enter the second number: ");
        int num2 = input.nextInt();
        
        int sum = num1 + num2;
        
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output:

Enter the first number: 5

Enter the second number: 7

The sum of 5 and 7 is: 12

Explanation:

In this example, we import the `Scanner` class and create a new `Scanner` object named `input`. We prompt the user to enter the first number using the `print()` method, and then we use the `nextInt()` method of the `Scanner` class to read an integer value from the user and store it in the variable `num1`. We repeat the process for the second number, storing it in the variable `num2`. We then add the two numbers and store the result in the variable `sum`. Finally, we display the sum using the `println()` method.

Real-life scenario:

Consider a grade calculation system for a school, where teachers need to input students' scores for two exams and calculate their total marks. By using the "User Input" method, teachers can enter the exam scores of each student, and the program will automatically calculate the total marks.

Method 3: Java Program to Add Two Numbers Using Command Line Arguments

Another way to add two numbers in Java is by utilizing command line arguments. This approach allows you to provide the numbers as arguments when executing the program. Let's see an example to add two numbers in Java awt:

public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
       
        int sum = num1 + num2;
        
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output (command line input):

java AddTwoNumbers 5 7

The sum of 5 and 7 is: 12

Explanation:

In this example, we declare two integer variables, `num1` and `num2`. We use the `parseInt()` method of the `Integer` class to convert the command line arguments (which are passed as strings) to integer values and assign them to `num1` and `num2`. We then add the two numbers and store the result in the variable `sum`. Finally, we display the sum using the `println()` method.

Real-life scenario:

Suppose you are building a command-line calculator application. Users can pass two numbers as command line arguments, and the application will use the "Command Line Arguments" method to add the provided numbers and display the sum as output without requiring any further user input.

Method 4: Java Program to Add Two Numbers Using sum() Method

In Java, we can add two numbers using different methods. Let's explore two such methods: using a user-defined method and using the `sum()` method.

a) By Using User-defined Method:

public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;        
        int sum = add(num1, num2);        
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
    
    public static int add(int a, int b) {
        return a + b;
    }
}

Output:

The sum of 5 and 7 is: 12

Explanation:

In this example, we create a user-defined method named `add` that takes two integer parameters, `a` and `b`, and returns their sum. Inside the `main()` method, we assign the values 5 and 7 to `num1` and `num2` respectively. We then call the `add()` method, passing `num1` and `num2` as arguments, and store the returned sum in the variable `sum`. Finally, we display the sum using the `println()` method.

Real-life scenario:

Imagine you are developing a banking system where you need to calculate the total balance of a customer's savings and checking accounts. Using the "User-defined Method" approach, you can create a method that takes the balances of both accounts as parameters and returns their sum.

b) By Using the `sum()` Method:

import java.util.Arrays;

public class AddTwoNumbers {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = sum(num1, num2);        
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
    
    public static int sum(int... numbers) {
        return Arrays.stream(numbers).sum();
    }
}

Output:

The sum of 5 and 7 is: 12

Explanation:

In this example, we import the `Arrays` class from the `java.util` package. We create a method named `sum` that accepts variable arguments (`...`) of type `int`. Inside the method, we use the `stream()` method of the `Arrays` class to convert the variable arguments into a stream. We then use the `sum()` method of the stream to calculate the sum of the numbers. In the `main()` method, we assign the values 5 and 7 to `num1` and `num2` respectively. We call the `sum()` method, passing `num1` and `num2` as arguments, and store the returned sum in the variable `sum`. Finally, we display the sum using the `println()` method.

Real-life scenario:

Let's say you are developing an inventory management system, and have a list of product quantities. You need to calculate the total quantity of all the products in stock. By using the sum() method, you can pass the product quantities as arguments and get the sum of all the quantities.

Method 5: Java Program to Add Three Numbers

Expanding our knowledge, let's look at adding three numbers in Java. We can extend the previous approaches to include an additional number. Here's an example:

int num1 = 5;
int num2 = 7;
int num3 = 3;
int sum = num1 + num2 + num3;
System.out.println("The sum of " + num1 + ", " + num2 + ", and " + num3 + " is: " + sum);

Output:

The sum of 5, 7, and 3 is: 15

Explanation:

In this example, we declare three integer variables, `num1`, `num2`, and `num3`, and assign them the values 5, 7, and 3 respectively. We then add the three numbers and store the result in the variable `sum`. Finally, we display the sum using the `println()` method.

Real-life scenario:

Consider a recipe app where users can input the quantities of three ingredients to get the total amount required for a particular dish. The "Sum of 3 Numbers" method can be utilized to add the quantities of the ingredients and display the total amount needed.

Method 6: Java Program to Add N Numbers Using Array and Loop

What if we want to add an arbitrary number of values? Let's explore a step-by-step approach with a diagram to understand how to sum N numbers in Java efficiently.

1. Declare and initialize variables

int n = 5; // Total numbers to be added
int[] numbers = {2, 4, 6, 8, 10}; // Array to store the numbers
int sum = 0; // Initialize sum to 0

2. Iterate over the array and calculate the sum

for (int i = 0; i < n; i++) {
    sum += numbers[i];
}

3. Display the sum

System.out.println("The sum of the given numbers is: " + sum);

Explanation:

In this example, we assume we have an array named `numbers` that stores N numbers. We declare an integer variable `n` to store the total number of values. We initialize the variable `sum` to 0, which will accumulate the sum of the numbers. We use a `for` loop to iterate over the array and add each number to the `sum` variable. Finally, we display the sum using the `println()` method.

Real-life scenario:

Assume you're creating a corporate sales analytics app. A customizable number of daily sales statistics may be needed to calculate total sales for a given time period. The "Sum of N Numbers" technique can be used to construct an input box for daily sales information. The program then calculates the period's total sales. Because sales information varies by time range, this approach lets users efficiently analyze sales success. These are some real-world examples of utilizing Java loops to sum n numbers. Loops give you the flexibility and efficiency to automate repetitive tasks, handle enormous amounts of data, and perform complex algorithms across different domains.

Conclusion

Adding two numbers in Java is a fundamental operation that can be achieved through various methods. We explored many approaches, such as direct summation, user input, command line arguments, and various method-based techniques. We've also seen alternatives like adding three numbers or an arbitrary number of integers using arrays and loops. Understanding these techniques will allow you to perform additions in Java more efficiently. So go ahead, put your newfound knowledge to use, and keep exploring the enormous world of Java programming!

FAQs

1. How can I create a Java program to add two numbers by taking input from the user using the Scanner class?

To create a Java program that adds two numbers using user input, you can use the Scanner class from java.util. This allows the user to enter two numbers at runtime, which the program then reads, adds using the + operator, and displays the result. This approach is useful in interactive applications where real-time input is required.

2. What is the process of addition of two numbers in Java using command line arguments?

In Java, command line arguments can be used to pass input values directly when the program is executed. These values are received as strings in the main(String[] args) method. You need to convert them using Integer.parseInt() and then perform the addition of two numbers. This is particularly useful in automation or batch-processing scenarios.

3. How do command line arguments in Java work for performing arithmetic operations like addition?

Command line arguments in Java allow data to be passed into a program from the terminal. When adding two numbers using this method, both numbers are provided at runtime and parsed into integers. You then simply use the + operator to calculate the sum of two numbers and print the result using System.out.println().

4. What is a beginner-friendly way to write a Java program to add two numbers?

A beginner-friendly approach is to declare two integer variables, assign values to them manually, and then add them using the + operator. This method is helpful for learners who are new to Java and want to understand basic syntax and variable usage before moving to dynamic input methods like Scanner or command line arguments.

5. Can you explain how to perform the sum of two numbers using command line arguments in Java with an example?

Yes. Here's a quick example:

int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;

This code takes two arguments passed during program execution, adds them, and stores the result in sum. This is one of the simplest ways to demonstrate the addition of two numbers using command line arguments in Java.

6. How can we use Java methods to add two numbers and display the result?

You can write a method in Java like int add(int a, int b) that performs the addition and returns the result. In your main() method, you can call this function with two numbers passed either manually or through user input. This makes the program modular and reusable—especially useful when implementing Java programs to add two numbers using methods.

7. Is it possible to write a Java program that uses both Scanner input and a separate method for addition?

Yes, it’s a good practice. You can collect user input using Scanner, then pass the input values to a method that performs the addition. This way, you separate logic and input handling, making your code cleaner and more maintainable. It's a practical way to demonstrate addition of two numbers in Java by taking input from user and using a method.

8. What are some different ways to add two numbers in Java?

You can add two numbers in Java using several approaches:

  • Manually assigned values
  • User input with Scanner
  • Command line arguments
  • Using methods

Each method has its own use case depending on the complexity and interactivity of the application.

9. How do you write a Java program to add two numbers using the + operator only?

To add two numbers using only the + operator, you simply declare and initialize two variables and then use sum = num1 + num2;. This basic operation is the foundation of all arithmetic logic in Java, making it crucial for beginners to understand.

10. Why is it important to understand addition of two numbers in Java for beginners?

Understanding how to perform the addition of two numbers in Java teaches you core programming concepts like variables, data types, operators, and input/output. It forms the foundation for learning more advanced programming topics such as loops, conditions, and functions.

11. Can you write a complete Java program to add two numbers using command line arguments and explain it?

Certainly. Here's a complete example:

public class AddNumbers {
public static void main(String[] args) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}

In this program, two numbers are passed via command line, parsed to integers, added using the + operator, and printed. It's a clean demonstration of how to use command line arguments in Java to add two numbers.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

text

Foreign Nationals

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.