The Math.toIntExact() method returns the integer value of a long type. An exception is thrown if the argument’s value overflows that of an int.


Math.toIntExact(long value)

In the function Math.toIntExact(long value), the parameter value is of type long. The function will return an int.

If the value of value is greater than 2147483647L or is less than -2147483648L, then the following exception will be thrown:

Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.toIntExact


The following example demonstrates the application of .toIntExact() method:

// Check.java
public class Check {
public static void main(String args[]) {
long val= 2147483647L;

This results in the following output:



Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Java on Codecademy