Java program to add two numbers using method

Let’s learn java program to add two numbers using method.

Java program to add two numbers using method

In this post we are going to learn addition of two numbers in java using method in two ways, one, by creating a method and other using sum() method of Integer class.

In the below program on addition of two numbers in java using method first user enters two numbers as input using nextInt() method of Scanner class.

These two numbers are stored in integer variables ‘num1’ and ‘num2’ and then passed as parameters to addTwoNumbers() method.

Lastly addTwoNumbers() method returns sum of two numbers to “main” method. Here’s the java program to add two numbers using function.

import java.util.Scanner;
public class AddTwoNumbers
{
   public static void main(String[] args)
   {
      int num1, num2, sum;
      Scanner sc = new Scanner(System.in);
      System.out.println("First number : ");
      num1 = sc.nextInt();
      System.out.println("Second number : ");
      num2 = sc.nextInt();
      sum = addTwo(num1, num2);
      System.out.println("Sum : " + sum);
      sc.close();
   }
   public static int addTwo(int a, int b)
   {
      int sum = a + b;
      return sum;
   }
}


Output:

First number : 25
Second number : 63
Sum : 88


Now let’s add two numbers using sum() method of Integer class. sum() method adds two integers together as per the + operator.

Syntax:

public static int sum(int a, int b)

Parameters:

a the first operand

b the second operand

Returns:

the sum of a and b

NOTE: If both arguments are negative the result will be negative.

Here’s an example to add two numbers using sum() method of Integer class.

public class AddTwoNumbersUsingMethod
{
   public static void main(String[] args)
   {
      int num1 = 36;
      int num2 = 39;
      System.out.println("The sum of " + num1 + " and " + num2 + " is: " + Integer.sum(num1, num2));
   }
}


Output:

The sum of 36 and 39 is: 75


Let’s see another example to add two numbers using sum() method of Integer class.

public class AddTwoNumbersUsingMethod
{
   public static void main(String[] args)
   {
      int num1 = -36;
      int num2 = -139;
      System.out.println("The sum of " + num1 + " and " + num2 + " is: " + Integer.sum(num1, num2));
   }
}


Output:

The sum of -36 and -139 is: -175

Also read – nested classes in java