Java Tutorial Java Advanced Java References

Java Math - negateExact() Method



The Java negateExact() method returns the negation of the argument. The method can be overloaded and it can take int and long arguments. It throws an exception, if the result overflows an int or a long.

Syntax

public static int negateExact(int x)  
public static long negateExact(long x)  

Parameters

x Specify the value.

Return Value

Returns the negation of the argument.

Exception

Throws ArithmeticException, if the result overflows an int or a long.

Example:

In the example below, negateExact() method is used to negate the argument.

public class MyClass {
 public static void main(String[] args) {
  int i = 5;
  long j = 145;
  System.out.println(Math.negateExact(i)); 
  System.out.println(Math.negateExact(j));
  System.out.println();

  int p = -2;
  long q = -150;
  System.out.println(Math.negateExact(p)); 
  System.out.println(Math.negateExact(q));
 }
}

The output of the above code will be:

-5
-145

2
150

❮ Java Math Methods

5