bhylu.com

Advertisements

Java Use Math with Domain and Overflow Checks

Math provides numeric operations, but each operation still has a valid domain and a result type. A convenient method name does not remove those constraints.

Understand the idea

sqrt works with double values; a negative real input produces NaN rather than a useful real root. min and max select values without validating their meaning. Exact integer methods such as addExact throw ArithmeticException on overflow instead of silently wrapping. Rounding methods have different contracts, especially for halfway and negative values. Read the specific method’s result type before assigning its answer.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        int total = Math.addExact(230, 175);
        System.out.println(total);
        System.out.println(Math.sqrt(81));
        System.out.println(Math.floorDiv(-7, 3));
        System.out.println(Math.floorMod(-7, 3));
    }
}

Expected output

405
9.0
-3
2

The exact addition checks the integer sum. Floor division rounds the quotient toward negative infinity, unlike ordinary integer division’s truncation toward zero. The paired floor modulus then satisfies the corresponding quotient/remainder relationship. These choices matter for grouping, bucketing and cyclic offsets involving negative values.

Check the official Java documentation for detailed contracts and supported options.