For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
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.
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.
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.
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.
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.
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.
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.
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
for (int i = 0; i < n; i++) {
sum += numbers[i];
}
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.
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!
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.
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.
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().
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.
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.
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.
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.
You can add two numbers in Java using several approaches:
Each method has its own use case depending on the complexity and interactivity of the application.
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.
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.
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
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.
Recommended Programs