What is Math.toIntExact() in Java?
The toIntExact method takes a single long argument and returns the int value of the passed value. The toIntExact method is a static method present in the Math class.
Syntax
public static int toIntExact(long a);
Argument
a: The long value to be converted toint.
Return value
This method returns the int value of the long argument.
The toIntExact method is equivalent to:
long value to int value
Example
import java.lang.Math;class ToIntExactTest {public static void main(String cmdArgs[]) {long a = 1000l;int intA = Math.toIntExact(a);System.out.print("The int value of "+ a + " is ");System.out.println(intA);long b = -1234l;int intB = Math.toIntExact(a);System.out.print("The int value of "+ b + " is ");System.out.println(intB);}}
In the code above:
-
We created two variables,
aandb, of thelongtype. -
We called
toIntExactwithaas an argument. This will return an equivalentintvalue ofa. We did the same for variableb.
The toIntExact method will throw ArithmeticException if the long value overflows the int value.
Example
For example, the ArithmeticException will be thrown if the value of the argument is lesser than the minimum value or greater than the maximum value that the int type can hold.
import java.lang.Math;class ToIntExactTest {public static void main(String cmdArgs[]) {try{long a = 33333333333l;int intVal = Math.toIntExact(a);}catch(Exception e) {System.out.println(e);}}}
In the code above, we created a variable, a, of the long type. We assigned the 33333333333l value to the a variable.
When we call the toIntExact method with a as an argument, we will get ArithmeticException because the 33333333333l value is greater than the value an integer can hold.