What is the BigInteger.add method in Java?

The add method of the BigInteger class can add the passed BigInteger object value with the called BigInteger object value.

Syntax


public BigInteger add(BigInteger val)

Argument

This method takes a BitInteger object as an argument.

Return value

This method returns a BitInteger object. The value of the returned BigInteger object is the sum of the argument and the current BigInteger object value.

Code

The example below demonstrates how to use the add method.

import java.math.BigInteger;
class BigIntegerAddExample {
public static void main( String args[] ) {
BigInteger val1 = new BigInteger("1000");
BigInteger val2 = new BigInteger("100");
BigInteger result = val1.add(val2);
System.out.println(result);
}
}

Explanation

In the code above, we do the following:

  • Line 1, we import the BigInteger class.

import java.math.BigInteger;

  • Lines 5 and 6, we create two BigInteger objects: val1 with value 1000 and val2 with value 100.

BigInteger val1 = new BigInteger("1000");
BigInteger val2 = new BigInteger("100");

  • Line 7, we call the add method on the val1 object with val2 as an argument.
  • This returns a BigInteger which has a value equal to the sum of val1 and val2.

BigInteger result = val1.add(val2); //1100

Free Resources