toIntExact()
方法的语法是:
Math.toIntExact(long value)
这里,
toIntExact()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
toIntExact() 参数
toIntExact()
方法接受一个参数。
int
返回的参数
toIntExact() 返回值
从指定的long
值返回int
值
示例 1: Java Math.toIntExact()
class Main { public static void main(String[] args) { // create long variable long value1 = 52336L; long value2 =-445636L; // change long to int int num1 = Math.toIntExact(value1); int num2 = Math.toIntExact(value2); // print the int value System.out.println(num1); // 52336 System.out.println(num2); //-445636 } }
在上面的示例中,我们使用
Math.toIntExact()
方法从指定的
long
变量中获取
int
值。
示例 2: Math.toIntExact() 引发异常
如果返回的
int
值不在
int
数据类型的范围内,
toIntExact()
方法会抛出异常。
class Main { public static void main(String[] args) { // create a long variable long value = 32147483648L; // convert long into int int num = Math.toIntExact(value); System.out.println(num); } }
在上面的例子中,
long
变量的值是
32147483648。当我们将 long 变量转换为
int
时,结果值超出了
int
数据类型的范围。
因此,
toIntExact()
方法会抛出
整数溢出
异常。