# Java Program to Add Two Numbers Using Functions

In this post, we will learn how to add two numbers using functions in Java Programming language. Let’s see the Java Program to add two numbers using functions.

Contents

## Java Program to Add Two Numbers Using Functions

```import java.util.*;

public class Main{

public static int sum(int num1, int num2){
int ans = num1 + num2;
return ans;
}

public static void main(String[] args){
Scanner sc = new Scanner(System.in);

System.out.println("Enter the first number: ");
int n1 = sc.nextInt();

System.out.println("Enter the second number: ");
int n2 = sc.nextInt();

int sum = sum(n1,n2);

System.out.println("The sum of "+n1+" and "+n2+" is "+sum);

}

}```

Output

``````Enter the first number: 12
Enter the second number: 34
The sum of 12 and 34 is 46``````

## How Does This Program Work ?

``````Scanner sc = new Scanner(System.in);

System.out.println("Enter the first number: ");
int n1 = sc.nextInt();

System.out.println("Enter the second number: ");
int n2 = sc.nextInt();``````

First, the user is asked for two numbers. We are taking input from the user using the Scanner class in Java.

In this program, we have created a parameterized function “sum” with two parameters i.e. num1, num2 and we are returning the sum of the two numbers i.e. return num1 + num2.

``````public static int sum(int num1, int num2){
int ans = num1 + num2;
return ans;
}``````

Then we call the function sum and receive the answer returned by the function in the sum variable

``int sum = sum(n1,n2);``

Then, we just display the result i.e. the addition of two numbers. This is the Java Program to Add Two Numbers Using Functions.

## Conclusion

I hope after going through this post, you understand how to code Java Program to Add Two Numbers Using Functions.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Also Read: