Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

longvalueexact
biginteger
java
communitycreator

# What is BigInteger.longValueExact() method in Java?

Programming Bytes

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.

### Syntax

public long longValueExact()


### Parameters

This method doesn’t take any argument.

### Output

This method returns the BigInteger value as a long value.

### Code

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);
}

}
}

### Explanation

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

longvalueexact
biginteger
java
communitycreator

CONTRIBUTOR

Programming Bytes
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time