Java Tutorial Java Advanced Java References

Java Math - toIntExact() Method



The Java 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.

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:4)

❮ Java Math Methods