Open In App

Java Math toIntExact() Method

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Math.toIntExact() method in Java is a part of the java.lang.Math package. This method is used to convert a long value to an int value. If the long value fits within the range of an int, the method returns it as an int. But if the value is too big or too small for an int, it throws an ArithmeticException.

This method is helpful for type conversion from long to int in Java when range checks are required.

Syntax of toIntExact() Method

public static int Math.toIntExact(long value)

  • Parameters: value: This is the long value we want to convert.
  • Return Value: It returns the value of the argument as an int if it is within the range.
  • Exception: It throws an ArithmeticException if the value is outside the valid int range.

Working of toIntExact() Method

  • The toIntExact() method checks whether the long values falls within the range of the int type.
  • If the value is within range, it returns the equivalent int.
  • If it is out of the range of an int, an ArithmeticException is thrown to avoid incorrect results due to overflow.

Examples of Java Math toIntExact() Method

Example 1: In this example, we are converting a valid long value.

Java
// Java program to demonstrate
// Math.toIntExact() with a valid long value
import java.lang.Math;

public class Geeks {

    public static void main(String[] args) {
        long value = 599;

        System.out.println("Converted int value: " 
        + Math.toIntExact(value));
    }
}

Output
Converted int value: 599


Example 2: In this example, we are converting Long.MAX_VALUE which is a case of overflow.

Java
// Java program to demonstrate
// Math.toIntExact() throwing an exception on overflow
import java.lang.Math;

public class Geeks {

    public static void main(String[] args) {
        long value = Long.MAX_VALUE;

        System.out.println("Converted int value: " 
        + Math.toIntExact(value));
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: integer overflow

Explanation: The Long.MAX_VALUE is greater than the maximum value an int can store. So, an exception is thrown to prevent incorrect data conversion.


Next Article
Practice Tags :

Similar Reads