negateExact()
方法的语法是:
Math.negateExact(num)
这里,
negateExact()
是一个静态方法。因此,我们使用类名访问该方法,
Math
。
negateExact() 参数
negateExact()
方法接受一个参数。
注意: 参数的数据类型应该是int或long。
negateExact() 返回值
反转指定参数的符号后返回值示例 1: Java Math.negateExact()
class Main { public static void main(String[] args) { // create int variables int a = 65; int b =-25; // negateExact() with int arguments System.out.println(Math.negateExact(a)); //-65 System.out.println(Math.negateExact(b)); // 25 // create long variable long c = 52336L; long d =-445636L; // negateExact() with long arguments System.out.println(Math.negateExact(c)); //-52336 System.out.println(Math.negateExact(d)); // 445636 } }
在上面的例子中,我们使用了带有
int
和
long
变量的
Math.negateExact()
方法来反转各自的变量。
示例 2: Math.negateExact() 引发异常
如果否定结果溢出数据类型,
negateExact()
方法会抛出异常。即结果应在指定变量的数据类型范围内。
class Main { public static void main(String[] args) { // create a int variable // minimum int value int a =-2147483648; // negateExact() with the int argument // throws exception System.out.println(Math.negateExact(a)); } }
在上面的例子中,
a 的值是最小的
int
值。这里,
negateExact()
方法改变了变量
a 的符号。
-(a)
=>-(-2147483648)
=> 2147483648 // out of range of int type
因此,
negateExact()
方法会抛出
整数溢出
异常。