Java Math decrementExact()

decrementExact() 方法的语法是

Math.decrementExact(num)

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


decrementExact() 参数

decrementExact() 方法接受一个参数。

  • num -从中减去1的参数

注意:参数的数据类型应为 intlong


decrementExact() 返回值

  • 返回从参数中减去 1 后的值

示例 1:Java Math.decrementExact()

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

    // create a int variable
    int a = 65;

    // decrementExact() with the int argument
    System.out.println(Math.decrementExact(a));  // 64

    // create a long variable
    long c = 52336L;

    // decrementExact() with the long argument
    System.out.println(Math.decrementExact(c));  // 52335
  }
}

在上面的示例中,我们使用 Math.decrementExact() 方法与 intlong 变量一起,从各自的变量中减去 1


示例 2:Math.decrementExact() 引发异常

如果减法结果溢出了数据类型,decrementExact() 方法将引发一个异常。也就是说,结果应在指定变量的数据类型的范围内。

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

    // create a int variable
    // minimum int value
    int a = -2147483648;

    // decrementExact() with the int argument
    // throws exception
    System.out.println(Math.decrementExact(a));
  }
}

在上面的示例中,a 的值是最小的 int 值。在这里,decrementExact() 方法从 a 中减去 1

   a - 1  
=> -2147483648 - 1
=> -2147483649    // out of range of int type     

因此,decrementExact() 方法会引发 integer overflow 异常。


另请阅读

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

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

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

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