decrementExact() 方法的语法是
Math.decrementExact(num)
在这里,decrementExact() 是一个静态方法。因此,我们使用类名 Math 来访问该方法。
decrementExact() 参数
decrementExact() 方法接受一个参数。
- num -从中减去1的参数
注意:参数的数据类型应为 int 或 long。
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() 方法与 int 和 long 变量一起,从各自的变量中减去 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 异常。
另请阅读