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 addition of 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 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 above java program to add two numbers using function.

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