You are here

Java program to add two numbers

Java program to add two numbers, a user enters two integers, and we calculate their sum and display it. Using int data type, we can add numbers up to a limit (range of int data type). If you want to add very large numbers, then you may use BigInteger class.

Addition of two numbers in Java

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);
   }
}

You can use the float data type to add two floating-point numbers.

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

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

Java program to add two 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);
  }
}

Output of program:

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

In the program, 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.

Share this