liveBook · Manning

Math.floorMod

As explained in 100 Java Mistakes and How to Avoid Them

Math.floorMod is a Java method that computes a floor-modulus result with a nonnegative remainder for a positive modulus.

Math.floorMod(dividend, divisor) computes a floor-modulus result whose sign follows the divisor. With a positive divisor, the result is nonnegative, unlike Java’s remainder operator when the dividend is negative. section 4.4 section 4.5

Normalize a possibly negative angle

The remainder expression can produce an invalid negative result: int normalized = angle % 360;. Use int normalized = Math.floorMod(angle, 360); to map positive and negative angles into the 0–359 interval. section 4.5

Hash-code indexing

Replacing Math.abs(obj.hashCode()) % NUMBER_OF_NODES with Math.floorMod(obj.hashCode(), NUMBER_OF_NODES) avoids the Integer.MIN_VALUE failure and keeps a positive node count within range. section 4.4

Use Math.floorMod when:

  • A dividend may be negative and the result must stay nonnegative for a positive divisor. section 4.5
  • Avoiding Math.abs(... ) % divisor is important because Math.abs(Integer.MIN_VALUE) remains negative. section 4.4
  • Do not use remainder-based random range generation; use Random.nextInt(bound) for a correct, uniform range. section 4.4

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains sign behavior and supplies corrected Java snippets, but stops short of implementation internals.
Examples
Uses angle normalization, hash-code node selection, and random-number range generation as practical cases.
What it assumes
Assumes familiarity with Java integer arithmetic, the remainder operator, and method calls.
What you can do after
Apply Math.floorMod to normalize negative inputs and replace unsafe absolute-value remainder expressions.
How it connects
Contrasts with the remainder operator and Math.abs, and relates to Integer.MIN_VALUE, hash indexing, oddness checks, and random number generation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.