# Addition Of Two Numbers In Java With Program Examples

One of the four basic math operations is addition. The others are subtraction, multiplication, and division. When you add two whole numbers together, you get the total amount, also called the sum of the numbers.

In Java, it’s very easy to find the sum of two or more numbers. First, name and set the values of two variables in sum.

Another place to store the total number of things. Apply the (+) operator between the variables that have been declared and store the result.

For Example:

``````class Main {

public static void main(String[] args) {

System.out.println("Enter two numbers");

// declares a numbers int

int first = 20;

int second = 30;

System.out.println(first + " " + second);

int sum = first + second;

System.out.println("The sum is: " + sum);

}

}``````

Output:

``50``

## Addition of Two Numbers Using Command Line Arguments

In Java, command-line arguments are passed to the Java program to add when it runs. Using command-line arguments in a program is very easy. They are kept in the String array that is passed to the args[] parameter of the main() method.

``````public class SumOfNumbers4

{

public static void main(String args[])

{

int x = Integer.parseInt(args); //first arguments

int y = Integer.parseInt(args); //second arguments

int num1 = x + y;

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

}

}``````

Output:

``The sum of x and y is: 101``

## Addition of two numbers using java scanner class

In Java, the scanner class allows the program to read what the user inputs. We ask for two numbers as num1 and send them to the user-defined sum method().

For Example:

``````//declared a string args scanner

import java.util.Scanner;
public class SumOfNumbers2

{

public static void main(String args[])

{

int x, y, sum;

Scanner sc = new Scanner(System.in);

System.out.print("Enter the first number: ");

x = sc.nextInt();

System.out.print("Enter the second number: ");

y = sc.nextInt();

sum = sum(x, y);

System.out.println("The sum of two numbers x and y is: " + sum);

}

//method that calculates the sum and prints the sum

public static int sum(int a, int b)

{

int sum = a + b;

return sum;

}

}``````

Output:

``````Enter the first number: 26

Enter the second number: 34

The sum of two numbers x and y is: 60``````

## Conclusion

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.