Java program to add two numbers

Let’s learn java program to add two numbers.

Java program to add two numbers

addition program in java is most common java interview question.

In the below java code to add two numbers we are taking input from user using nextInt() method of Scanner class.

First user enters two numbers. Then these two numbers are stored in two integer variables ‘a’ and ‘b’.

Lastly two numbers are added using “+” operator. Let’s see sum of two numbers using Scanner or program to add two numbers taking input from user.

import java.util.Scanner;
public class AddTwoNumbers
{
   public static void main(String[] args)
   {
      int a, b, c;
      System.out.println("Please enter two integers to add : ");
      Scanner sc = new Scanner(System.in);
      a = sc.nextInt();
      b = sc.nextInt();
      c = a + b;
      System.out.println("Sum of two numbers = " + c);
      sc.close();
   }
}


Output:

java program to add two numbers

Now let’s see how to add two numbers where we are specifying value of both numbers in the program.

public class AddTwoNumbersDemo
{
   public static void main(String[] args)
   {
      int a = 5, b = 5, sum;
      sum = a + b;
      System.out.println("Sum of two integers : " + sum);
   }
}


Output:

10