The java.lang.StrictMath.toIntExact() is an inbuilt method in Java is used to return the value of the long argument. If the result overflows an int it will throw an exception. Object creation is not mandatory as toIntExact(long num) is static.
Syntax:
public static int toIntExact(long num)
Parameters: The method accepts one parameter num of long type whose int value is returned.
Return Value: The method returns the argument as an int.
Exception: If the argument overflows an int it throws ArithmeticException.
Examples:
Input: num = 2727l
Output: 2727
Input: num = -86262l
Output: -86262
Below programs illustrate the java.lang.StrictMath.toIntExact() method:
Program 1:
import java.lang.StrictMath;
class Geeks {
public static void main(String args[])
{
long num = 266526l;
int intvalue = StrictMath.toIntExact(num);
System.out.print( "IntExact value of "
+ num + " = " + intvalue);
}
}
|
Output:
IntExact value of 266526 = 266526
Program 2:
import java.lang.StrictMath;
class Geeks {
public static void main(String args[])
{
long num = -7226526l;
int intvalue = StrictMath.toIntExact(num);
System.out.print( "IntExact value of "
+ num + " = " + intvalue);
}
}
|
Output:
IntExact value of -7226526 = -7226526
Program 3: To demonstrate ArithmeticException
import java.lang.StrictMath;
class Geeks {
public static void main(String args[])
{
try {
long num = 654456645546l;
System.out.println( "Trying to get "
+ "IntExact value of: "
+ num);
int intvalue = StrictMath.toIntExact(num);
System.out.print( "IntExact value of "
+ num + " = " + intvalue);
}
catch (Exception e) {
System.out.println( "Exception thrown: " + e);
}
}
}
|
Output:
Trying to get IntExact value of: 654456645546
Exception thrown: java.lang.ArithmeticException: integer overflow