VOOZH about

URL: https://www.geeksforgeeks.org/java/java-8-biginteger-longvalueexact-method-with-examples/

⇱ Java 8 | BigInteger longValueExact() Method with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java 8 | BigInteger longValueExact() Method with Examples

Last Updated : 4 Dec, 2018
java.math.BigInteger.longValueExact() was introduced in Java 8. It is an inbuilt function which converts the value of BigInteger to a long and checks for lost information. If the value of BigInteger is greater than 9,223,372,036,854,775,807 or less than -9,223,372,036,854,775,808; the method will throw ArithmeticException as BigInteger doesn’t fit in long range. Syntax:
public long longValueExact()
Return Value: This method returns the long value of this BigInteger. Exception: The method throws ArithmeticException if the value of BigInteger is greater than 9,223,372,036,854,775,807 or less than -9,223,372,036,854,775,808; as this range doesn’t fit in long range. Example:
Input: 98169894145
Output: 98169894145
Explanation: 98169894145 is given as input which is BigInteger
and long value of 98169894145 is 98169894145

Input: -65416518651
Output: -65416518651
Explanation: -65416518651 is given as input which is BigInteger 
and long value of -65416518651 is -65416518651

Input: 10000000000000000000
Output: ArithmeticException
Explanation: When 10000000000000000000 is tried to convert to long,
since 10000000000000000000 > 9,223,372,036,854,775,807 (greater than a long's range), 
therefore it throws an arithmetic exception.
Below programs illustrates longValueExact() method of BigInteger class: Program 1: To demonstrate longValueExact() method for positive number <9,223,372,036,854,775,807
Output:
BigInteger value : 98169894145
long converted value : 98169894145
Program 2: To demonstrate longValueExact() method for negative number >-9,223,372,036,854,775,808
Output:
BigInteger value : -65416518651
long converted value : -65416518651
Program 3: To demonstrate longValueExact() method for negative number <-9,223,372,036,854,775,808. It will throw Arithmetic Exception
Output:
BigInteger value : -10000000000000000000
Exception: java.lang.ArithmeticException: BigInteger out of long range
Program 4: To demonstrate longValueExact() method for positive number >9,223,372,036,854,775,807. It will throw Arithmetic Exception
Output:
BigInteger value : 10000000000000000000
Exception: java.lang.ArithmeticException: BigInteger out of long range
Reference: https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#longValueExact--
Comment