# Java Program to Add Two Numbers

• Java program to find sum of two numbers.
• Write a java program to add two numbers and print it on screen.

To add two numbers in a java program, we will first take two integers as input from user using Scanner and store them in a integer variable num1 and num2. Then we add num1 and num2 using + arithmetic operator and store it in integer variable "sum". Finally, we print the sum of two given integers on screen.

## Java Program to Find Sum of Two Numbers

```package com.tcc.java.programs;

import java.util.*;

/**
* Java Program to find sum of two numbers
*/
public class SumTwoNumbers {
public static void main(String[] args) {
int num1, num2, sum;
Scanner scanner;

scanner = new Scanner(System.in);

// Take two integer input from user and
// store it in variable num1 and num2
System.out.println("Enter First Number");
num1 = scanner.nextInt();

System.out.println("Enter Second Number");
num2 = scanner.nextInt();

// Add two numbers using + operator
sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " = " + sum);
}
}
```
Output
```Enter First Number
5
Enter Second Number
7
Sum of 5 and 7 = 12
```

## Java Programs to Find Sum of Two Numbers using Function

This Java program is similar to above program except here we are using a user defined function getSum to calculate the sum of two integers. The function getSum takes two integer arguments and returns the sum of both input parameters.

```package com.tcc.java.programs;

import java.util.*;

/**
* Java Program to find sum of two numbers using function
*/
public class SumTwoNumbersFunction {

public static void main(String[] args) {
int num1, num2, sum;
Scanner scanner;

scanner = new Scanner(System.in);

// Take two integer input from user and
// store it in variable num1 and num2
System.out.println("Enter First Number");
num1 = scanner.nextInt();

System.out.println("Enter Second Number");
num2 = scanner.nextInt();

/*
* Call getSum by passing num1 and num2 as parameter
*/
sum = getSum(num1, num2);
System.out.println("Sum of " + num1 + " and " + num2 + " = " + sum);

}

/**
* Function to add two numbers
*/
public static int getSum(int num1, int num2) {
int sum;
sum = num1 + num2;
return sum;
}
}
```
Output
```Enter First Number
9
Enter Second Number
12
Sum of 9 and 12 = 21
```

Recommended Posts
 Java Program to Add Subtract Multiply and Divide Two Numbers Java Program to Swap Two Numbers Java Program to Check Odd or Even Numbers Java Program to Find Largest of Three Numbers Java Program to Check Whether a Number is Positive or Negative Java Program to Find LCM and GCD of Two Numbers Java Program to Find All Factors of a Number Java Program to Find Sum of Digits of a Number Java Program to Count Number of Digits in a Number Java Program to Make a Simple Calculator using Switch Statement Java Program to Convert Decimal to Binary Numbers All Java Programs
 Previous Next