java.math.BigInteger longValueExact()


On this document we will be showing a java example on how to use the longValueExact() method of BigInteger Class. Basically this method Converts this BigInteger to a long, checking for lost information. If the value of this BigInteger is out of the range of the long type, then an ArithmeticException is thrown.

The checking of lost of information is somewhat necessary because the BigInteger has a lot more precision than long so basically when we do narrowing, there are cases that we might lose some precision. If the case wherein there would be some lost of information, an ArithmeticException will be thrown.

For reference the long range is from -9223372036854775808 to 9223372036854775807 and these information is readily available through the Long constants Long.MIN_VALUE and Long.MAX_VALUE.

Method Syntax

public long longValueExact()

Method Argument

Data Type Parameter Description

Method Returns

The longValueExact() method returns this BigInteger converted to primitive long.


Requires Java 1.8 and up

Java BigInteger longValueExact() Example

Below is a java code demonstrates the use of longValueExact() method of BigInteger class. The example presented might be simple however it shows the behavior of the longValueExact() method.


import java.math.BigInteger;
import java.util.Scanner;

 * A java example source code to demonstrate
 * the use of longValueExact() method of BigInteger class

public class BigIntegerLongValueExactExample {

	public static void main(String[] args) {

		// Declare and initialize our BigInteger values
		BigInteger val1 = new BigInteger("12");
		//BigInteger val2 = new BigInteger("10223372036854775807");
		BigInteger val2 = new BigInteger("15");

		// get the long equivalent of each BigInteger
		long longVal1 = val1.longValueExact();
		long longVal2 = val2.longValueExact();

		// print the operation
		System.out.println("val1 in long is " + longVal1);
		System.out.println("val2 in long is " + longVal2);



This example is a lot simpler than it looks. We only initialize two BigInteger, one is certainly within range and the other is also within range but we have included a value that is certainly outside of range but commented out. We have commented the value that is outside the range because it will throw an ArithmeticException and we don’t want that. This swill clearly be simulated on below example output.

Sample Output

Below is the sample output when you run the above example.

BigInteger longValueExact() example output