
Java Math negateExact()方法反转指定数字的符号并返回它。
negateExact()方法的语法为:
Math.negateExact(num)
注意:negateExact()是静态方法。因此,我们可以使用Math类名来访问该方法。
negateExact()参数
num - 要反转其符号的参数
注意:参数的数据类型应为int或long。
negateExact()返回值
反转指定参数的符号后返回值
示例1:Java Math.negateExact()
class Main {
public static void main(String[] args) {
//创建整型变量
int a = 65;
int b = -25;
//带int参数的negateExact()
System.out.println(Math.negateExact(a)); // -65
System.out.println(Math.negateExact(b)); // 25
//创建long变量
long c = 52336L;
long d = -445636L;
//带long参数的NegateExact()
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) {
//创建int变量。
//最小int值
int a = -2147483648;
//带int参数的NegateExact()。
//抛出异常
System.out.println(Math.negateExact(a));
}
}在上面的示例中,a的值为最小值int。在此,negateExact()方法更改变量a的符号。
-(a) => -(-2147483648) => 2147483648 // out of range of int type
因此,negateExact()方法引发integer overflow异常。