You are here

Java program to add two numbers

Java program to add two numbers: A user will enter two integers and we will calculate their sum and then display it. First 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 (see second program).

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class AddNumbers
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int x, y, z;
  8.  
  9.       System.out.println("Enter two integers to calculate their sum");
  10.       Scanner in = new Scanner(System.in);
  11.      
  12.       x = in.nextInt();
  13.       y = in.nextInt();
  14.       z = x + y;
  15.      
  16.       System.out.println("Sum of the integers = " + z);
  17.    }
  18. }

Download Add numbers program class file. You can also create a method which returns the sum of two integers which are passed to it as arguments.

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

Java program to add large numbers using BigInteger class

  1. import java.util.Scanner;
  2. import java.math.BigInteger;
  3.  
  4. class AddingLargeNumbers {
  5.   public static void main(String[] args) {
  6.     String number1, number2;
  7.     Scanner in = new Scanner(System.in);
  8.  
  9.     System.out.println("Enter first large number");
  10.     number1 = in.nextLine();
  11.  
  12.     System.out.println("Enter second large number");
  13.     number2 = in.nextLine();
  14.  
  15.     BigInteger first  = new BigInteger(number1);
  16.     BigInteger second = new BigInteger(number2);
  17.     BigInteger sum;
  18.    
  19.     sum = first.add(second);
  20.        
  21.     System.out.println("Result of addition = " + sum);
  22.   }
  23. }

Output of program:

  1. Enter first large number
  2. 11111111111111
  3. Enter second large number
  4. 99999999999999
  5. Result of addition = 111111111111110

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.

Download Adding Large numbers program class file.