Java program to add two numbers

Let’s learn java program to add two numbers.

Java program to add two numbers

Java program to add two integers is most common java interview question. In this java program to add two numbers we are taking input from user.

Also read – variables in java

First user enters two numbers. Then these two numbers are stored in two variables. Lastly two numbers are added using “+” operator. Let’s see java code,

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 addition of two numbers in java without using scanner,

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



Output:

10

Similarly we can execute java program to add two numbers using function – click here.