What is the BigInteger.abs() method in Java?

In Java, the BigInteger class handles mathematical operations involving integers outside the limits of all primitive types.

The abs() method of the BigInteger gets the absolute valueThe absolute value of a number X is the non-negative value of x without considering its sign of the BigInteger object.

Syntax

The syntax of the abs() method is as follows:

public BigInteger abs()

Arguments

This method doesn’t take any argument.

Return value

This method returns a BigInteger object that has the absolute value of the current BigInteger object value.

Code

The example below demonstrates the use of the abs() method:

import java.math.BigInteger;
class BigIntegerAbsExample {
public static void main( String args[] ) {
BigInteger val1 = new BigInteger("-123123");
BigInteger result = val1.abs();
System.out.println(result);
}
}

Explanation

In the code above:

  • In line number 1, we import the BigInteger class.
import java.math.BigInteger;
  • In line number 5, we create a BigInteger object val1 with the value -123123.
BigInteger val1 = new BigInteger("-123123");
  • In line number 6, we call the abs() method on the val1 object. This method call returns a BigInteger object. The value in the returned BigInteger object is equal to the absolute value of the val1 object, i.e., 123123.
BigInteger result = val1.abs(); //123123

Free Resources