decrementExact()
方法的语法是:
Math.decrementExact(num)
这里,
decrementExact()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
decrementExact() 参数
decrementExact()
方法接受一个参数。
注意: 参数的数据类型应该是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 } }
在上面的例子中,我们使用了带有
int
和
long
变量的
Math.decrementExact()
方法来减去 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()
方法会抛出
整数溢出
异常。