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) {

    // 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() 方法抛出 integer overflow(整数溢出)异常。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战