java.lang.Math.toIntExact()

Description

On this document we will be showing a java example on how to use the toIntExact(long value) method of Math Class. The toIntExact(long value) returns the value of the long argument; throwing an exception if the value overflows an int.

Most of the methods of the Math class is static and the toIntExact() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.toIntExact(value).

From the first part we have described this method to throw an exception if the result overflows the specified data type. If you are interested on the limit of the result before it throws an exception, you can find it using Integer.MIN_VALUE and Integer.MAX_VALUE.

With the complicated description above on this method functionality, you might start to wonder why not directly convert from long to int. That might be the easiest solution though if we breach the limitation of data type the result would be inconsistent which probably would happen because long can handle higher values than int, not unlike if we use the toIntExact() which has the capability to throw an exception if the result overflows of its range. So with this capability to throws an exception, will give us room to provide mechanism to handle such scenario.

Notes:

  • ArithmeticException will be throw if the result of the operation overflows int.

Method Syntax

public static int toIntExact(long value)

Method Returns

The toIntExact() method returns the argument as an int.

Compatibility

Requires Java 1.8 and up

Java Math toIntExact() Example

Below is a java code demonstrates the use of toIntExact() method of Math class. The example presented might be simple however it shows the behaviour of the toIntExact() method.

The above java example source code demonstrates the use of toIntExact() method of Math class. There are two values initially declared value1 and value2. The first value certainly is within range of the int however the second one is more that the maximum value as defined by Integer.MAX_VALUE. So at first part we have used casting to convert the long to int values and as expected the result would be wrong on the conversion of the second value.

The second part is we have converted the values into int using the Math.toIntExact and we have also used try-catch in order to handle the exception when in such case that values intended to be converted to int is not within range. This example shows on how we can leverage the exception that can be thrown when the conversion is not proper.

Sample Output

Below is the sample output when you run the above example.

java lang Math toIntExact() example output