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 to int.

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, a and b, of the long type.

  • We called toIntExact with a as an argument. This will return an equivalent int value of a. We did the same for variable b.


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.

Free Resources