Sum of Numbers in Java
Sum of Two Numbers in Java
In Java, finding the sum of two or more numbers is very easy. First, declare and initialize two variables to be added. Another variable to store the sum of numbers. Apply mathematical operator (+) between the declared variable and store the result. The following program calculates and prints the sum of two numbers.
The sum of numbers is: 340
Sum of Two Numbers in Java Using Method
There are two ways to find the sum of two numbers in Java.
By Using User-defined Method
The Java Scanner class allows us to read input from the user. We take two numbers as input and pass them to the user-defined method sum(). The following program calculates the sum of two numbers using the method and prints the result.
Enter the first number: 34 Enter the second number: 12 The sum of two numbers x and y is: 46
By Using Integer.sum() Method
The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator. It can be overloaded and accepts the arguments in int, double, float, and long.
It returns the sum of the numbers that are passed as an argument. It throws ArithmaticException when the result overflows an integer value.
Note: If both arguments are negative, the result will be negative.
The sum of x and y is: 88 The sum of x and y is: -38
Similarly, we can calculate the sum of double, float, and long type numbers.
Sum of Two Numbers Using Command Line Arguments in Java
The command-line arguments are passed to the program at run-time. Passing command-line arguments in a Java program is quite easy. They are stored as strings in the String array passed to the args parameter of the main() method in Java.
The sum of x and y is: 101
First, compile the above program by using the command javac SumOfNumbers4.java. After that, run the program by using the command java SumOfNumbers4 89 12. Where 89 and 12 are command-line arguments.
Sum of Three Numbers in Java
The program for the sum of three numbers is the same as the sum of two numbers except there are three variables.
Enter the first number: 12 Enter the second number: 34 Enter the third number: 99 The sum of three numbers x, y, and z is: 145
Sum of N Numbers in Java
Let's implement the above steps in a Java program.
Enter Number of Numbers to be Calculated: 4 Enter the number: 12 Enter the number: 13 Enter the number: 5 Enter the number: 4 The sum of the numbers is: 34