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:val1with value10, andval2with value9223372036854775808. -
We call the
byteValueExactmethod of theval1object. This returns theBigIntegervalue asbyte. The value10can be stored inbyte, so there is no exception. -
We call the
byteValueExactmethod of theval2object. The value128is too large to be stored inbyte. So, anArithmeticExceptionis thrown.