Library contents

Java Math.negateExact

Reverse the sign of an integer with an overflow check.

A simple example

Math.negateExact

  1. Start with 3
  2. Do this Change the sign
  3. Result −3
The positive integer 3 has a representable negative counterpart.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.negateExact(3));
    }
}
Output
-3

Syntax

Java syntax
Math.negateExact(adjustment)
JDK 21 method signatures (2)
public static int negateExact(int a)
public static long negateExact(long a)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Reverse an inventory adjustment

A stock ledger changes as units are sold or an adjustment is reversed. Follow the sign of the operation carefully so the remaining inventory reflects the actual movement of goods.

From the programint adjustment = -18
Result18
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int adjustment = -18;
        System.out.println(Math.negateExact(adjustment));
    }
}
Output
18

Reversing a deduction of eighteen restores eighteen units.

Advertisements

Reverse a mistaken delivery

A librarian posted an increase of nine books to the wrong shelf. She enters the opposite signed adjustment to undo the entry.

Given9
Worked result-9

Using 9 gives -9 for this measurement.

Undo a duplicate withdrawal

The stock journal includes a duplicate debit of four items. Its reversal needs the same magnitude with the opposite sign.

Given-4
Worked result4

Using -4 gives 4 for this measurement.

What to watch for

The most negative signed integer has no positive counterpart of the same width.

Documentation for Math.negateExact