![]() |
VOOZH | about |
The Math.toIntExact() method in Java is a part of the java.lang.Math package. This method is used to convert a long value to an int value. If the long value fits within the range of an int, the method returns it as an int. But if the value is too big or too small for an int, it throws an ArithmeticException.
This method is helpful for type conversion from long to int in Java when range checks are required.
public static int Math.toIntExact(long value)
Example 1: In this example, we are converting a valid long value.
Converted int value: 599
Example 2: In this example, we are converting Long.MAX_VALUE which is a case of overflow.
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflowExplanation: The Long.MAX_VALUE is greater than the maximum value an int can store. So, an exception is thrown to prevent incorrect data conversion.