Sum of Numbers in JavaIn this section, we will create Java programs to find the sum or addition of two numbers using the method and commandline arguments, the sum of three numbers, and the sum of n numbers. Sum of Two Numbers in JavaIn 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. SumOfNumbers1.java Output: The sum of numbers is: 340 Sum of Two Numbers in Java Using MethodThere are two ways to find the sum of two numbers in Java.
By Using Userdefined MethodThe Java Scanner class allows us to read input from the user. We take two numbers as input and pass them to the userdefined method sum(). The following program calculates the sum of two numbers using the method and prints the result. SumOfNumbers2.java Output: Enter the first number: 34 Enter the second number: 12 The sum of two numbers x and y is: 46 By Using Integer.sum() MethodThe 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. Syntax: 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.SumOfNumbers3.java Output: 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 JavaThe commandline arguments are passed to the program at runtime. Passing commandline 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. SumOfNumbers4.java Output: 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 commandline arguments. Sum of Three Numbers in JavaThe program for the sum of three numbers is the same as the sum of two numbers except there are three variables. SumOfNumbers5.java Output: 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. SumOfNumbers6.java Output: 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
Next TopicPower of a Number in Java
