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) {

    // 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
  }
}

在上面的示例中,我们使用了 Math.negateExact() 方法处理 intlong 变量,以反转相应变量的符号。


示例 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() 方法会抛出 integer overflow 异常。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战