The syntax of the toIntExact() method is:
Math.toIntExact(long value)
Here, toIntExact() is a static method. Hence, we are accessing the method using the class name, Math.
toIntExact() Parameters
The toIntExact() method takes a single parameter.
- value - argument which is to be returned as an
int
toIntExact() Return Value
- returns the
intvalue from the specifiedlongvalue
Example 1: Java Math.toIntExact()
In the above example, we have used the Math.toIntExact() method to get an int value from the specified long variable.
Example 2: Math.toIntExact() Throws Exception
The toIntExact() method throws an exception if the returned int value is not within the range of the int data type.
In the above example, the value of the long variable is 32147483648. When we convert the long variable into an int, the resulting value is out of the range of the int data type.
Hence, the toIntExact() method throws the integer overflow exception.