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

Simple java program for adding two numbers is the most common java interview question.

In the below program 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 program to add two numbers using method.

// addition program in java
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


Also read – nested classes in java