Library contents

Java Math.absExact

Return the magnitude of a signed integer, reporting an unrepresentable result.

A simple example

Math.absExact

  1. Start with −3
  2. Do this Measure distance from zero
  3. Result 3
From −3, three unit steps reach zero. The magnitude is 3.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.absExact(-3));
    }
}
Output
3

Syntax

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

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

java Main.java

Measure a stock change and detect overflow

Two signed readings can be individually valid while their difference or magnitude exceeds the destination type. Check the arithmetic at its boundaries before reporting the size of the change.

From the programint change = -18
Result18
Main.java

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

The size of a drop of eighteen items is eighteen.

Advertisements

Count missing lab probes

A storeroom log records an adjustment of minus 14 probes after an audit. The supervisor needs its magnitude for a discrepancy ticket.

GivenStock change −14
Worked result14

The absolute magnitude fits in a signed integer.

Close a balanced shift

A till already balances when its last receipt is entered. The auditor still needs to record the discrepancy as a number.

GivenStock change 0
Worked result0

Zero has magnitude zero.

What to watch for

The minimum signed integer raises ArithmeticException. Widen first if its magnitude should be representable.

Documentation for Math.absExact