Java Math toIntExact()

The Java Math toIntExact() method returns the int value from the specified long argument.

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 int value from the specified long value

Example 1: Java Math.toIntExact()

class Main {
  public static void main(String[] args) {

    // create long variable
    long value1 = 52336L;
    long value2 = -445636L;

    // change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);

    // print the int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

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.

class Main {
  public static void main(String[] args) {

    // create a long variable
    long value = 32147483648L;

    // convert long into int
    int num = Math.toIntExact(value);
    System.out.println(num);
  }
}

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.


Recommended Tutorials