What is the BigInteger.subtract method in Java?

The subtract method of the BigInteger class subtracts the passed BigInteger object value from the called BigInteger object value.

Syntax

public BigInteger subtract(BigInteger val)

Argument

This method takes a BitInteger object as an argument.

Return value

this - val

This method returns a BitInteger object. The value of the returned BigInteger object is the difference between the current BigInteger object value and the BigInteger argument’s value.

Code

The example below demonstrates the use of the subtract method:

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

Explanation

In the code above:

  • In line number 1, we import the BigInteger class.
import java.math.BigInteger;
  • In lines number 5 and 6, we create two BigInteger objects, val1 with the value 1000 and val2 with 100.
BigInteger val1 = new BigInteger("1000");
BigInteger val2 = new BigInteger("100");
  • In line number 7, we call the subtract method on the val1 object with val2 as an argument. This method call will return a BigInteger, which has a value equal to the difference between the val1 and val2.
BigInteger result = val1.subtract(val2); //900

Free Resources