Java program to add two numbers

Let’s learn java program to add two numbers.

Java program to add two numbers

Simple java program to add two numbers is most common java interview question. In this java program to add two numbers 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 WAP in java to add two numbers without using scanner class,

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 above java program using method – click here.