Table of Contents
ToggleAddition two numbers in java is a fundamental concept in programming. This article explains different techniques to add two numbers in Java. We will discuss:
- Standard approach Using hardcoded values
- Standard approach Using User Input Values
- Standard approach Using Command Line Arguments
- User Defined Method
- Inbuilt Sum() function
So, let’s get started.
Addition Of Two Numbers In Java
Before proceeding to solutions let’s first understand the problem statement with examples.
Problem Statment
Write a program that takes two numbers as input and add two numbers in Java.
For Example:
Enter the first number: 10
Enter the second number: 20
Output:
The sum of 10 and 20 is: 30
Different Ways To Add Two Numbers In Java
Let’s look into different ways how we can add two numbers in Java.
1. Standard approach Using Hardcoded Values
In this approach, the values of the two numbers are directly specified within the code, and there’s no user input involved.
Addition Program In Java By Using Hardcoded Input Values
// Java program to add two numbers
public class AdditionExample {
public static void main(String[] args) {
int num1 = 5;
int num2 = 7;
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}
Output
The sum of 5 and 7 is: 12
Explanation
The values of num1
and num2
are directly assigned in the code. The program calculates their sum and prints the result.
2. Standard approach Using User Input Values
In this approach, the values of the two numbers are taken as input from the user during runtime using the Scanner
class.
Addition Program In Java Using User Input Values
// Java program to add two numbers by taking user input
import java.util.Scanner;
public class UserInputAddition {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate the sum of the two numbers
int sum = num1 + num2;
// Display the result
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
// Close the Scanner to prevent resource leak
scanner.close();
}
}
Output
Enter the first number: 8
Enter the second number: 6
The sum of 8 and 6 is: 14
Explanation
The program prompts the user to input two numbers, reads the values using the Scanner
class, calculates their sum, and then prints the result.
3. Standard approach Using Command Line Argument
In this approach, the values of the two numbers are provided as command-line arguments during program execution.
In Java, command-line arguments are passed to the main
method when a program is executed from the command line. The main
method has a parameter called args
, which is an array of strings. Each element in this array corresponds to a command-line argument.
When you run a Java program from the command line, you can include additional values after the program’s name.
java YourProgramName arg1 arg2
You can access individual command-line arguments by indexing into the args
array.
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
Here, args[0]
is the first command-line argument, and args[1]
is the second.
Addition Program In Java By Using Command Line arguments
public class CommandLineAddition {
public static void main(String[] args) {
// Check if exactly two command-line arguments are provided
if (args.length != 2) {
System.out.println("Please provide two numbers as command-line arguments.");
return;
}
// Parse the first command-line argument as an integer
int num1 = Integer.parseInt(args[0]);
// Parse the second command-line argument as an integer
int num2 = Integer.parseInt(args[1]);
// Calculate the sum of the two numbers
int sum = num1 + num2;
// Display the result
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
}
Output
$ java CommandLineAddition 3 9
The sum of 3 and 9 is: 12
Explanation
The program checks if two command-line arguments are provided. If yes, it converts them to integers and calculates their sum, then prints the result. If not, it prompts the user to provide the required inputs.
4. Using User-Defined Function
In this approach, we utilise a user-defined function to encapsulate the addition logic, making the code modular and reusable.
Addition Program In Java Using User Defined Function
import java.util.Scanner;
public class UserDefinedFunctionAddition {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Call the user-defined function to add two numbers
int result = addNumbers(num1, num2);
// Display the result
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);
// Close the Scanner to prevent resource leak
scanner.close();
}
// User-defined function to add two numbers
public static int addNumbers(int a, int b) {
return a + b;
}
}
The addNumbers
function takes two integers as parameters, adds them, and returns the result.
Output
Enter the first number: 5
Enter the second number: 7
The sum of 5 and 7 is: 12
Explanation
The main
method takes user input, calls the addNumbers
function to perform the addition, and then displays the result.
5. Using Inbuilt Sum() Method
In Java, the Integer.sum()
method is a utility method introduced in Java 8 to simplify the addition of two integer values. It provides a convenient and efficient way to add two integers without the need for manual casting or arithmetic operations.
Addition Program In Java Using Sum() Method
public class AddTwoNumbers {
public static void main(String[] args) {
// Two numbers to be added
int num1 = 5;
int num2 = 10;
// Using Integer.sum() to add two numbers
int sum = Integer.sum(num1, num2);
// Displaying the result
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
}
}
Output
Sum of 5 and 10 is: 15
Explanation
In the above example the Integer.sum()
method is used to add num1
and num2
, and the result is stored in the variable sum
.
Sum of n Numbers
Till now we discussed how to add two numbers in Java, let’s now generalise the approach to find sum on n numbers in java.
Approach
- Use a loop to take input from the user
n
times. - Accumulate the entered numbers to calculate the sum.
- Display the final sum.
Addition Of N Numbers Program In Java
import java.util.Scanner;
public class SumOfUserProvidedNumbers {
public static void main(String[] args) {
// Scanner to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the value of n
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
// Initialize sum to store the cumulative sum
int sum = 0;
// Take input from the user n times
for (int i = 1; i <= n; i++) {
System.out.print("Enter number " + i + ": ");
int num = scanner.nextInt();
sum += num;
}
// Close the scanner to avoid resource leak
scanner.close();
// Display the result
System.out.println("Sum of the entered " + n + " numbers is: " + sum);
}
}
Output
Enter the value of n: 3
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Sum of the entered 3 numbers is: 60
Explanation
- The above program uses a
Scanner
to take user input for the value ofn
. - A
for
loop is employed to iterate from 1 ton
. - Inside the loop, the program prompts the user to enter a number, reads the input, and adds it to the
sum
variable. - After the loop completes, the program prints the sum of the entered
n
numbers. In the provided example, it displays “Sum of the entered 3 numbers is: 60“.
Key Takeaways
- Hardcoded values can be added directly but don’t allow customization
- User input with Scanner class enables dynamic specification of numbers
- Command-line arguments provide values when invoking the Java program
- Custom methods modularize the addition logic for reuse
- Utility methods like Integer.sum() simplify built-in operations
- Loops allow adding larger sets of numbers entered by the user
Checkout more Java Tutorials here.
Similar Posts
Add Days To The Current Date in Java
Calculate Area of Hexagon in Java
Program to Calculate EMI in Java
Calculate Area of a Circle in Java
I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.
FAQ
How to add two numeric string in Java?
To add two numeric strings in Java, you can convert them to integers using Integer.parseInt()
or to doubles using Double.parseDouble()
, perform the addition, and then convert the result back to a string if needed. Here’s a concise example:
String numStr1 = "10";
String numStr2 = "20";
int sum = Integer.parseInt(numStr1) + Integer.parseInt(numStr2);
String result = String.valueOf(sum);
In this example, Integer.parseInt()
converts the numeric strings to integers, and the addition is performed. The result is then converted back to a string using String.valueOf()
.
How to add numbers in set in Java?
To add numbers in a set in Java, use the HashSet
or another set implementation from the java.util
package. Here’s a concise example:
import java.util.HashSet;
import java.util.Set;
public class AddNumbersToSet {
public static void main(String[] args) {
// Create a HashSet to store numbers
Set<Integer> numberSet = new HashSet<>();
// Add numbers to the set
numberSet.add(5);
numberSet.add(10);
numberSet.add(15);
// Display the set
System.out.println("Numbers in the set: " + numberSet);
}
}
In this example, a HashSet
is used to store unique numbers. The add()
method is then used to add numbers to the set. Finally, the contents of the set are displayed.
How do you add three numbers in Java?
To add three numbers in Java, declare three variables, read their values from the user or assign them directly, and then perform the addition. Here’s a concise example:
import java.util.Scanner;
public class AddThreeNumbers {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Prompt the user to enter the third number
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
// Close the scanner to avoid resource leaks
scanner.close();
// Calculate the sum of the three numbers
int sum = num1 + num2 + num3;
// Display the result
System.out.println("Sum of the three numbers is: " + sum);
}
}
This code snippet adds three numbers entered by the user and prints the result. The Scanner
is used to read input, and the sum is calculated and displayed.