You are here

Java program to add two numbers

Java program to add two numbers: Given below is the code of a Java program that adds two numbers which are entered by a user.

Java programming source code

import java.util.Scanner;
 
class AddNumbers
{
   public static void main(String args[])
   {
      int x, y, z;
 
      System.out.println("Enter two integers to calculate their sum");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
      z = x + y;
 
      System.out.println("Sum of the integers = " + z);
   }
}

Download Add numbers program class file.

Output of program:
Output of Java program to add two numbers

This program can only add numbers which can be stored in 4 bytes (size of integer data type), if you wish to add very large numbers, then you can use BigInteger class.

Java program to add large numbers using BigInteger class

import java.util.Scanner;
import java.math.BigInteger;
 
class AddingLargeNumbers {
  public static void main(String[] args) {
    String number1, number2;
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter first large number");
    number1 = in.nextLine();
 
    System.out.println("Enter second large number");
    number2 = in.nextLine();
 
    BigInteger first  = new BigInteger(number1);
    BigInteger second = new BigInteger(number2);
    BigInteger sum;
 
    sum = first.add(second);
 
    System.out.println("Result of addition = " + sum);
  }
}

In our code, we create two objects of BigInteger class of java.math package. Input should be digit strings otherwise an exception will be thrown; also you cannot just use '+' operator to add objects of BigInteger class, you have to use the add method for addition of two objects.

Output of program:

Enter first large number
11111111111111
Enter second large number
99999999999999
Result of addition = 111111111111110

Download Adding Large numbers program class file.