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()
方法1减去从 。
a - 1
=> -2147483648 - 1
=> -2147483649 // out of range of int type
因此, decrementExact()
方法将引发integer overflow
异常。
推荐的教程
- Math.incrementExact()
- Math.negateExact()