Java Math toIntExact() Method
The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int.
Syntax:
public static int toIntExact (long value)
Parameters:
The parameter ‘value’ represents the long value.
Return Value:
The toIntExact () method returns an int value.
Throws:
The toIntExact () method throws:
ArithmeticException- if the argument overflows an int
Example 1:
public class JavaMathToIntExactExample1 {
public static void main(String[] args) {
Long a=-985565437l;
//returns the int value of the given long argument
System.out.println("Int value of "+ a+" is "+Math.toIntExact(a));
}
}
Output:
Int value of -985565437 = -985565437
Example 2:
public class JavaMathToIntExactExample2 {
public static void main(String[] args) {
Long a=0l;
//returns zero, if argument is zero
System.out.println("Int value of "+ a+" is "+Math.toIntExact(a));
}
}
Output:
Int value of 0 is 0
Example 3:
public class JavaMathToIntExactExample3 {
public static void main(String[] args) {
Long a=Long.MIN_VALUE;
//throws an exception if the value overflows an int
System.out.println("Int value of "+ a+" is "+Math.toIntExact(a));
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.lang.Math.toIntExact(Math.java:1011) at com.TutorialAndExamples.JavaMathToIntExactExample3.main(JavaMathToIntExact Example3.java:7)
Example 4:
public class JavaMathToIntExactExample4 {
public static void main(String[] args) {
Long a=Long.MIN_VALUE;
//throws an exception if the value overflows an int
System.out.println("Int value of "+ a+" is "+Math.toIntExact(a));
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.lang.Math.toIntExact(Math.java:1011) at com.TutorialAndExamples.JavaMathToIntExactExample4.main(JavaMathToIntExact Example4.java:7)
