Lesson · Java Language Fundamentals
Numeric semantics: division, remainders, and Math
12 min readNumeric Semantics & the Math Class
How Java divides and what % really returns, the rounding family in Math, overflow-checked arithmetic that throws instead of wrapping, and the bit utilities every wrapper ships with.
Division and remainder, signed
Integer division truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. The remainder operator % then keeps the sign of the dividend, so 7 % 3 is 1 and -7 % 3 is -1. Those two functions are consistent with each other and with nothing else in mathematics, which is fine until you expected mathematical modulo.
The mathematical versions live beside them in Math. floorDiv rounds toward negative infinity and floorMod returns a result with the divisor's sign, so Math.floorMod(-7, 3) is 2. The practical rule: cyclic indexing, calendar math and hash bucketing from possibly negative values want floorMod; the plain operators are for when the signs are known positive or parity does not matter.
Division by zero splits by type. Integer division throws ArithmeticException. Floating-point division produces Infinity, -Infinity or NaN, because IEEE 754 defines those results instead of failing.
- 7 / 2 is 3, -7 / 2 is -3: truncation toward zero.
- 7 % 3 is 1, -7 % 3 is -1: the remainder follows the dividend.
- Math.floorDiv(-7, 2) is -4: rounding toward negative infinity.
- Math.floorMod(-7, 3) is 2: the modulo most people picture.
Math lab
pick an expressionInteger division truncates toward zero. Add a decimal point to an operand when the fraction matters: 7 / 2.0 is 3.5.
The Exact family and floorMod both fail loudly on purpose. The plain operators never will.
The rounding family
Math has four ways to round, and their names lie a little. floor goes down, ceil goes up, rint rounds to the nearest even number (IEEE's default), and round adds 0.5 and floors, which is why Math.round(-2.5) is -2 and not -3. Round half away from zero is simply not what round does.
Return types matter too: Math.round(double) returns a long, Math.round(float) returns an int, and both can only be trusted for inputs that actually fit their destination. For money, none of these belong in the picture at all; that is BigDecimal territory from the numbers chapter.
Overflow, checked
The arithmetic operators never complain about overflow; the Math family with Exact in the name does. addExact, subtractExact, multiplyExact, incrementExact, decrementExact, negateExact and toIntExact throw ArithmeticException the moment the result does not fit. They are the right tools for counters that must not wrap, money paths, and anywhere a silent corruption is worse than a loud failure.
Two standard traps belong here as well. Math.abs(Integer.MIN_VALUE) returns MIN_VALUE itself, because the positive counterpart does not exist in an int; use Math.abs((long) x) when it matters. And the famous midpoint (lo + hi) / 2 overflows for large ints, so binary search and friends compute lo + (hi - lo) / 2 instead.
Bit utilities on the wrappers
Integer and Long carry a small toolkit worth knowing by name: bitCount (population count), highestOneBit, numberOfLeadingZeros, numberOfTrailingZeros, reverse, reverseBytes, rotateLeft and rotateRight. Formatting and parsing get the same treatment: toBinaryString, toHexString, parseInt(text, radix), and the unsigned suite (toUnsignedLong, compareUnsigned, divideUnsigned, parseUnsignedInt) that lets 32 bits behave like an unsigned value where a protocol demands it.
None of this needs memorising. The point is that when a bit-level problem appears, the JDK has usually already written and tested the loop you were about to type.
Math.abs(Integer.MIN_VALUE) is negative
Ints range from -2147483648 to 2147483647, so the minimum has no positive twin. abs returns the minimum itself, silently negative. The same asymmetry bites negateExact (it throws) and every bit of code that assumes abs makes numbers safe. Widen to long first when the sign matters.
Interview angles
What is the difference between % and Math.floorMod?+
% is a remainder: the result keeps the dividend's sign, so -7 % 3 is -1. floorMod is a modulus: the result keeps the divisor's sign, so floorMod(-7, 3) is 2. Cyclic indexing over possibly negative values wants floorMod.
What does Math.round(-2.5) return?+
-2. round is defined as floor(x + 0.5), so it rounds half UP in the numeric sense, not away from zero. For round-half-away-from-zero or banker's rounding, reach for BigDecimal's RoundingMode, which names its behaviour explicitly.
How do you detect integer overflow?+
Use the checked Math family: addExact, multiplyExact and friends throw ArithmeticException on overflow instead of wrapping. Alternatively compute in a wider type and range-check. Plain operators and compound assignments never signal anything.
How do you compute a midpoint of two large ints safely?+
lo + (hi - lo) / 2 instead of (lo + hi) / 2. The first stays within range for any lo and hi inside the int domain; the second overflows when both are large, which is exactly the binary-search bug everyone ships once.