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 the below java program we are taking input from user using nextInt() method of Scanner class.

Also read – variables in java

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 addition of two numbers in java using user input.

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 java program to add two numbers where we are specifying value of both numbers.

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


Similarly we can execute above sum of two numbers in java using method.

Meanwhile above java program can be executed using bufferedreader.


Addition of two numbers in java using objects

Let’s learn to print addition of two numbers in java using classes and objects or addition using class,

import java.util.Scanner;
class Add
{
   int addition = 0;
   Add(int number1, int number2)
   {
      addition = number1 + number2;
   }
}
public class UsingObjects 
{
   public static void main(String[] args) 
   {
      int num1, num2;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter first number: ");
      num1 = sc.nextInt();
      System.out.println("Please enter first number: ");
      num2 = sc.nextInt();
      Add obj = new Add(num1, num2);
      System.out.println("Addition of two numbers in java using objects: " + obj.addition);
      sc.close();
   }
}


Output:

Please enter first number: 59
Please enter first number: 83
Addition of two numbers in java using objects: 142


Also read – multiplication of two numbers in java


subtraction of two numbers in java

Now let’s learn subtraction of two numbers in java.

import java.util.Scanner;
public class SubtractionOfTwoNumbers
{
   public static void main(String[] args)
   {
      int num1, num2, subtraction;
      System.out.println("Please enter two numbers to substract: ");
      Scanner sc = new Scanner(System.in);
      num1 = sc.nextInt();
      num2 = sc.nextInt();
      subtraction = num1 - num2;
      System.out.println("subtraction of two numbers = " + subtraction);
      sc.close();
   }
}


Output:

Please enter two numbers to substract:
100
50
subtraction of two numbers = 50