What is the BigInteger.byteValueExact() method in Java?

The BigInteger class in Java handles calculations with big integral values that are beyond the limits of the primitive integer type.

The byteValueExact method of the BigInteger class converts the BigInteger value to a byte value.

An ArithmeticException is thrown if the value of this BigInteger is larger than the maximum value a byte type can hold.

Syntax

public byte byteValueExact()

This method doesn’t take any argument.

This method returns the BigInteger value as a byte value.

Code

The below code demonstrates how to use the byteValueExact method:

import java.math.BigInteger;
class ByteValueExact {
public static void main( String args[] ) {
BigInteger val1 = new BigInteger("10");
BigInteger val2 = new BigInteger("128");
System.out.println("ByteValueExact of " + val1 + " : "+ val1.byteValueExact());
try{
System.out.println("ByteValueExact of " + val2 + " : "+ val2.byteValueExact());
} catch(Exception e) {
System.out.println("Exception while converting the " + val2 + " - \n" + e);
}
}
}

Explanation

In the above code:

  • We create two BigIntegerobjects: val1 with value 10, and val2 with value 9223372036854775808.

  • We call the byteValueExact method of the val1 object. This returns the BigInteger value as byte. The value 10 can be stored in byte, so there is no exception.

  • We call the byteValueExact method of the val2 object. The value 128 is too large to be stored in byte. So, an ArithmeticException is thrown.

Free Resources