java.math.BigInteger longValueExact()
Description
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 |
---|---|---|
N/A | N/A | N/A |
Method Returns
The longValueExact() method returns this BigInteger converted to primitive long.
Compatibility
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.
package com.javatutorialhq.java.examples; 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.