In Java, the BigInteger
class handles calculations with very big integral values that are beyond the limits of the primitive integer type.
The longValueExact
method of the BigInteger
class converts the value of the BigInteger
to a long
value.
An ArithmeticException
is thrown if the value of this BigInteger
is larger than the maximum value a long
type can hold.
public long longValueExact()
This method doesn’t take any argument.
This method returns the BigInteger
value as a long
value.
The below code demonstrates how to use the longValueExact
method:
import java.math.BigInteger; class LongValueExact { public static void main( String args[] ) { BigInteger val1 = new BigInteger("10"); BigInteger val2 = new BigInteger("9223372036854775808"); System.out.println("LongValueExact of " + val1 + " : "+ val1.longValueExact()); try{ System.out.println("LongValueExact of " + val2 + " : "+ val2.longValueExact()); } catch(Exception e) { System.out.println("Exception while converting the " + val2 + " - \n" + e); } } }
In the above code:
We created two BigInteger
objects, val1
and val2
, with value 10
and 9223372036854775808
, respectively.
We called the longValueExact
method of the val1
object. This will return the BigInteger
value as long
. The value 10
can be stored in long
, so there will be no exception.
We called the longValueExact
method of the val2
object. The value 9223372036854775808
is too large to be stored in long
, so an ArithmeticException
is thrown.
RELATED TAGS
CONTRIBUTOR
View all Courses