Java program to add two numbers

Java program to add two numbers

In this tutorial we will learn writing Java programs to perform the addition of the two numbers. Or we can also say the sum of two numbers. We will see various ways like using the method, mathematic logic etc.

Program 1: Add two numbers in Java using operator

[java]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num1,num2,sum;
System.out.println(“Enter the value for num1 : “);
Scanner sc = new Scanner(System.in);
num1 = sc.nextInt();
System.out.println(“Enter the value for num2: “);
num2 = sc.nextInt();
sum = num1+num2;
System.out.println(“sum = “+sum );
}
}
[/java]

Output

Java program to add two numbers

In this program we have performed addition using the simple addition operator ‘+’. And after preforming the addition we have stored the value in sum variable.

After calculating the sum we have printed the output.

Program 2: Add two numbers in Java using sum() method

[java]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num1,num2,sum;
System.out.println(“Enter the value for num1 : “);
Scanner sc = new Scanner(System.in);
num1 = sc.nextInt();
System.out.println(“Enter the value for num2: “);
num2 = sc.nextInt();
sum=Integer.sum(num1, num2);
System.out.println(“sum = “+sum );
}
}
[/java]

Output

Java program to add two numbers

In this program we have used sum() function which is in built. Just passing the two parameter, this function will return the output by adding the two numbers.

Program 3: Add two numbers in Java using user defined method

[java]
import java.util.Scanner;
public class Main {
public static int add(int a, int b)
{
return a+b;
}
public static void main(String[] args) {
int num1,num2,sum;
System.out.println(“Enter the value for num1 : “);
Scanner sc = new Scanner(System.in);
num1 = sc.nextInt();
System.out.println(“Enter the value for num2: “);
num2 = sc.nextInt();
System.out.println(“sum = “+add(num1, num2));
}
}
[/java]

Output

Java program to add two numbers

In this program we have created own method named “add()” this function is taking two input as a parameter and returning the value after calculating the result.

So in this tutorial we have learn total three ways to write the addition program in java.