English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input and output (I/O)

Java Reader/Writer

Java other topics

Java Math negateExact() method usage and example

Java Math Mathematical Methods

The Java Math negateExact() method reverses the sign of the specified number and returns it.

The syntax of the negateExact() method is:

Math.negateExact(num)

Note: negateExact() is a static method. Therefore, we can use the Math class name to access this method.

negateExact() parameter

  • num - The parameter to be negated

Note: The parameter's data type should be int or long.

negateExact() return value

  • Returns the value after reversing the sign of the specified parameter

Example1: Java Math.negateExact()

class Main {
  public static void main(String[] args) {
    //Create an integer variable
    int a = 65;
    int b = -25;
    //NegateExact() with int parameter
    System.out.println(Math.negateExact(a));  // -65
    System.out.println(Math.negateExact(b));  // 25
    //Create a long variable
    long c = 52336L;
    long d = -445636L;
    //NegateExact() with long parameter
    System.out.println(Math.negateExact(c));  // -52336
    System.out.println(Math.negateExact(d));  // 445636
  }
}

In the above example, we used the Math.negateExact() method with int and long variables to reverse the signs of each variable.

Example2: Math.negateExact() throws an exception

If the negation result overflows the data type, the negateExact() method will throw an exception. That is, the result should be within the range of the specified variable's data type.

class Main {
  public static void main(String[] args) {
    //Create an int variable.
    //Minimum int value
    int a = -2147483648;
    //NegateExact() with int parameter.
    //Throw an exception
    System.out.println(Math.negateExact(a));
  }
}

In the above example, the value of a is the minimum value of int. Here, the negateExact() method changes the sign of the variable a.

   -(a)  
=> -(-2147483648)
=> 2147483648    // out of range of int type

Therefore, the negateExact() method triggers an integer overflow exception.

Recommended Tutorials

Java Math Mathematical Methods