跳到主要内容

Java Math negateExact() 方法

negateExact() 方法的语法是:

Math.negateExact(num)

这里,negateExact() 是一个静态方法。因此,我们通过类名 Math 来访问这个方法。

negateExact() 参数

negateExact() 方法接受一个参数。

  • num - 需要反转符号的参数

注意:参数的数据类型应该是 intlong

negateExact() 返回值

  • 返回反转指定参数符号后的值

示例 1:Java Math.negateExact()

class Main {
public static void main(String[] args) {

// 创建 int 变量
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
}
}

在上面的示例中,我们使用了 intlong 类型变量的 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 // 超出 int 类型的范围

因此,negateExact() 方法抛出了 整数溢出 异常。

推荐教程