incrementExact()
方法的语法是:
Math.incrementExact(num)
这里,
incrementExact()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
incrementExact() 参数
incrementExact()
方法接受一个参数。
注意: 参数的数据类型应该是int或long。
incrementExact() 返回值
返回参数加 1 后的值示例 1: Java Math.incrementExact()
class Main { public static void main(String[] args) { // create a int variable int a = 65; // incrementExact() with the int argument System.out.println(Math.incrementExact(a)); // 66 // create a long variable long b = 52336L; // incrementExact() with the long argument System.out.println(Math.incrementExact(b)); // 52337 } }
在上面的例子中,我们使用了
Math.incrementExact()
方法和
int
和
long
变量来添加 1 到相应的变量。
示例 2: Math.incrementExact() 抛出异常
如果加法结果溢出数据类型,
incrementExact()
方法会抛出异常。即结果应在指定变量的数据类型范围内。
class Main { public static void main(String[] args) { // create a int variable // maximum int value int a = 2147483647; // incrementExact() with the int argument // throws exception System.out.println(Math.incrementExact(a)); } }
在上面的例子中,
a 的值是
int
的最大值。在这里,
incrementExact()
方法将 1 添加到
a。
a + 1
=> 2147483647 + 1
=> 2147483648 // out of range of int type
因此,
incrementExact()
方法会抛出
整数溢出
异常。