Java Math negateExact()方法反轉(zhuǎn)指定數(shù)字的符號(hào)并返回它。
negateExact()方法的語(yǔ)法為:
Math.negateExact(num)
注意:negateExact()是靜態(tài)方法。因此,我們可以使用Math類名來訪問該方法。
num - 要反轉(zhuǎn)其符號(hào)的參數(shù)
注意:參數(shù)的數(shù)據(jù)類型應(yīng)為int或long。
反轉(zhuǎn)指定參數(shù)的符號(hào)后返回值
class Main { public static void main(String[] args) { //創(chuàng)建整型變量 int a = 65; int b = -25; //帶int參數(shù)的negateExact() System.out.println(Math.negateExact(a)); // -65 System.out.println(Math.negateExact(b)); // 25 //創(chuàng)建long變量 long c = 52336L; long d = -445636L; //帶long參數(shù)的NegateExact() System.out.println(Math.negateExact(c)); // -52336 System.out.println(Math.negateExact(d)); // 445636 } }
在上面的示例中,我們使用了帶有int和long變量的Math.negateExact()方法來反轉(zhuǎn)各個(gè)變量的符號(hào)。
如果求反的結(jié)果溢出數(shù)據(jù)類型,則negateExact()方法將引發(fā)異常。也就是說,結(jié)果應(yīng)在指定變量的數(shù)據(jù)類型范圍內(nèi)。
class Main { public static void main(String[] args) { //創(chuàng)建int變量。 //最小int值 int a = -2147483648; //帶int參數(shù)的NegateExact()。 //拋出異常 System.out.println(Math.negateExact(a)); } }
在上面的示例中,a的值為最小值int。在此,negateExact()方法更改變量a的符號(hào)。
-(a) => -(-2147483648) => 2147483648 // out of range of int type
因此,negateExact()方法引發(fā)integer overflow異常。