Java StrictMath toIntExact()方法及示例
java.lang.StrictMath.toIntExact() 是Java中一个内置的方法,用于返回长参数的值。如果结果溢出了一个int,它将抛出一个异常。由于toIntExact(long num)是静态的,所以创建对象不是强制性的。
语法。
public static int toIntExact(long num)
参数。该方法接受一个长类型的参数num,其值将被返回。
返回值。该方法将参数返回为一个int。
异常情况。如果参数溢出为一个int,则抛出 ArithmeticException
例子
输入: num = 2727l
输出:2727
输入: num = -86262l
输出:-86262
以下程序说明了java.lang.StrictMath.toIntExact()方法。
程序1 :
// Java program to demonstrate working
// of java.lang.StrictMath.toIntExact() method
import java.lang.StrictMath;
class Geeks {
// driver code
public static void main(String args[])
{
// Get the long value
// whose IntExact value is needed
long num = 266526l;
// Get the IntExact value
// using toIntExact() method
int intvalue = StrictMath.toIntExact(num);
// Print the IntExact value
System.out.print("IntExact value of "
+ num + " = " + intvalue);
}
}
输出:
IntExact value of 266526 = 266526
程序2
// Java program to demonstrate working
// of java.lang.StrictMath.toIntExact() method
import java.lang.StrictMath;
class Geeks {
// driver code
public static void main(String args[])
{
// Get the long value
// whose IntExact value is needed
long num = -7226526l;
// Get the IntExact value
// using toIntExact() method
int intvalue = StrictMath.toIntExact(num);
// Print the IntExact value
System.out.print("IntExact value of "
+ num + " = " + intvalue);
}
}
输出:
IntExact value of -7226526 = -7226526
程序3: 演示ArithmeticException
// Java program to demonstrate working
// of java.lang.StrictMath.toIntExact() method
import java.lang.StrictMath;
class Geeks {
// driver code
public static void main(String args[])
{
try {
// Get the long value
// whose IntExact value is needed
long num = 654456645546l;
System.out.println("Trying to get "
+ "IntExact value of: "
+ num);
// Get the IntExact value
// using toIntExact() method
int intvalue = StrictMath.toIntExact(num);
// Print the IntExact value
System.out.print("IntExact value of "
+ num + " = " + intvalue);
}
catch (Exception e) {
System.out.println("Exception thrown: " + e);
}
}
}
输出:
Trying to get IntExact value of: 654456645546
Exception thrown: java.lang.ArithmeticException: integer overflow