Java Math - toIntExact() Method
The java.lang.Math.toIntExact() method returns the value of the long argument. The method throws an exception if the value of the argument overflows an int.
Syntax
public static int toIntExact(long value)
Parameters
value |
Specify the long value. |
Return Value
Returns the value of the long argument. Throws an exception if the value overflows an int.
Exception
Throws ArithmeticException, if the argument overflows an int.
Example:
In the example below, toIntExact() method returns the value of the long argument.
import java.lang.*; public class MyClass { public static void main(String[] args) { System.out.println(Math.toIntExact(555)); System.out.println(Math.toIntExact(Long.MAX_VALUE)); } }
The output of the above code will be:
555 Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.toIntExact(Math.java:1071) at MyClass.main(MyClass.java:6)
❮ Java.lang - Math