跳到主要内容

Java Math toIntExact() 方法

toIntExact() 方法的语法是:

Math.toIntExact(long value)

这里,toIntExact() 是一个静态方法。因此,我们使用类名 Math 来访问这个方法。

toIntExact() 参数

toIntExact() 方法接受单个参数。

  • value - 需要被返回为 int 类型的参数

toIntExact() 返回值

  • 从指定的 long 值返回 int

示例 1:Java Math.toIntExact()

class Main {
public static void main(String[] args) {

// 创建 long 变量
long value1 = 52336L;
long value2 = -445636L;

// 将 long 转换为 int
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);

// 打印 int 值
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) {

// 创建一个 long 变量
long value = 32147483648L;

// 将 long 转换为 int
int num = Math.toIntExact(value);
System.out.println(num);
}
}

在上面的示例中,long 变量的值是 32147483648。当我们将 long 变量转换为 int 时,结果值超出了 int 数据类型的范围。

因此,toIntExact() 方法抛出了 integer overflow 异常。

推荐教程