Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
How + - * / % behave in Java, why 15 / 2 is 7, how remainder works with negative numbers, when to use Math.floorMod and floorDiv, the most useful Math methods (pow, sqrt, round, clamp…), overflow-safe exact methods, and StrictMath.
kvi5hnuCode Sprout team member10 min readOn this page
Operators combine values into new values. This article covers the arithmetic operators and the Math class, which supplies everything from square roots to rounding. The next two articles cover type conversions, then the increment, comparison, logical and bitwise operators.
The Five Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3 (integer division!) |
% | Remainder ("modulus") | 7 % 2 | 1 |
+ and - also work as unary operators (with one operand): -x negates x, and +x is just x.
Division: Integer or Floating-Point?
The / operator does two different things depending on its operands:
- If both operands are integers, it performs integer division: the result is an integer, and any fractional part is discarded (truncated toward zero).
- If at least one operand is floating-point (
floatordouble), it performs ordinary floating-point division.

public class Solution {
public static void main(String[] args) {
System.out.println(15 / 2); // integer division
System.out.println(15 % 2); // remainder
System.out.println(15.0 / 2); // floating-point division
System.out.println(15 / 2.0);
System.out.println(-15 / 2); // truncates toward zero
System.out.println(-15 % 2); // sign follows the dividend
System.out.println(15 % -2);
System.out.println(7.5 % 2); // % works on doubles too
}
}
7
1
7.5
7.5
-7
-1
1
1.5
Division by zero
| Expression | Result |
|---|---|
10 / 0 (integers) | throws ArithmeticException: / by zero |
10 % 0 (integers) | throws ArithmeticException: / by zero |
10.0 / 0 | Infinity |
0.0 / 0 | NaN |
Integer division by zero is a program error and throws an exception; floating-point division by zero follows the IEEE 754 rules described in the primitive-types article.
The Remainder Operator %
For integers, a % b is what's left after dividing a by b. It's used constantly:
| Task | Code |
|---|---|
Is n even? | n % 2 == 0 |
Last digit of n | n % 10 |
Is year divisible by 4? | year % 4 == 0 |
Wrap an index around an array of length len | (i + 1) % len |
| Every 100th iteration | if (count % 100 == 0) … |
Integer division and remainder always fit together: for any integers a and b (with b ≠ 0), (a / b) * b + a % b == a.
Remainder with negative numbers
Because integer division truncates toward zero (-15 / 2 is -7, not -8), the remainder takes the sign of the left operand (the dividend):
-15 % 2is-1, son % 2is0for evenn,1for odd positiven, and-1for odd negativen. That's whyn % 2 == 1is a wrong test for oddness. Usen % 2 != 0.15 % -2is1.
Mathematicians have long preferred a different rule (the Euclidean or "floored" remainder, which is never negative for a positive divisor). Early computer designers chose truncation instead, and most languages, Java included, inherited that choice. It's often inconvenient.
Math.floorMod and Math.floorDiv
Consider a 12-hour clock. The hour hand is at 2, and you go back 5 hours. Where is it?

public class Solution {
public static void main(String[] args) {
int hour = 2; // 2 o'clock
int adjustment = -5; // go back five hours
System.out.println((hour + adjustment) % 12); // -3: not a clock position
System.out.println(Math.floorMod(hour + adjustment, 12)); // 9
System.out.println(Math.floorDiv(-7, 2) + " vs " + (-7 / 2));
System.out.println(Math.ceilDiv(7, 2)); // Java 18+
}
}
-3
9
-4 vs -3
4
Math.floorMod(a, b)returns a remainder with the sign of the divisor. With a positive divisor it's always between0andb - 1, exactly what you want for clocks, calendars, circular buffers and hash buckets. (The old workaround was((a % b) + b) % b.)Math.floorDiv(a, b)rounds the quotient down (toward negative infinity) instead of toward zero:floorDiv(-7, 2)is-4.Math.ceilDiv(a, b)(Java 18+) rounds up. Useful for "how many pages of 10 do 95 items need?" →ceilDiv(95, 10)= 10.
With a negative divisor, floorMod gives a negative or zero result, but negative divisors are rare in practice.
The Math Class
Java has no operator for powers, square roots or trigonometry. Instead, the Math class provides them as static methods: you call them on the class name, Math.sqrt(x), rather than on an object. (Compare System.out.println(...), which operates on the object System.out. Static methods are explained in the objects and classes part.)
public class Solution {
public static void main(String[] args) {
System.out.println(Math.sqrt(16));
System.out.println(Math.pow(2, 10));
System.out.println(Math.cbrt(27));
System.out.println(Math.abs(-7.5));
System.out.println(Math.max(3, 9) + " " + Math.min(3, 9));
System.out.println(Math.round(2.5) + " " + Math.round(-2.5) + " " + Math.round(2.4));
System.out.println(Math.floor(-2.5) + " " + Math.ceil(-2.5) + " " + Math.rint(2.5));
System.out.println(Math.hypot(3, 4));
System.out.println(Math.sin(Math.PI / 2) + " " + Math.toDegrees(Math.PI));
System.out.println(Math.log(Math.E) + " " + Math.log10(1000) + " " + Math.exp(0));
System.out.println(Math.clamp(-1, 0, 10) + " " + Math.clamp(11, 0, 10) + " " + Math.clamp(3, 0, 10));
System.out.println(Math.PI + " " + Math.TAU + " " + Math.E);
}
}
4.0
1024.0
3.0
7.5
9 3
3 -2 2
-3.0 -2.0 2.0
5.0
1.0 180.0
1.0 3.0 1.0
0 10 3
3.141592653589793 6.283185307179586 2.718281828459045
Method reference
| Group | Methods | Notes |
|---|---|---|
| Powers and roots | pow(x, y), sqrt(x), cbrt(x), hypot(x, y) | pow takes and returns double; hypot = √(x² + y²) |
| Exponentials and logarithms | exp(x), log(x) (natural), log10(x), log1p(x), expm1(x) | log1p/expm1 are precise for tiny x |
| Trigonometry | sin, cos, tan, asin, acos, atan, atan2(y, x) | Angles in radians; convert with toRadians/toDegrees |
| Absolute value, min, max | abs(x), min(a, b), max(a, b) | Overloaded for int, long, float, double |
| Rounding | round(x), floor(x), ceil(x), rint(x) | See below |
| Range limiting | clamp(value, min, max) | Java 21+ |
| Integer helpers | floorDiv, floorMod, ceilDiv (18+), addExact etc. | See the overflow section |
| Random numbers | random() | A double in [0, 1); prefer java.util.Random or RandomGenerator for real use |
| Constants | Math.PI (π), Math.TAU (2π, Java 19+), Math.E (e) |
Rounding, precisely
| Method | Rule | 2.5 | -2.5 | 2.4 | Return type |
|---|---|---|---|---|---|
Math.round(x) | Nearest integer; halves round up (toward +∞) | 3 | -2 | 2 | long (or int for a float argument) |
Math.rint(x) | Nearest integer; halves round to the even neighbour | 2.0 | -2.0 | 2.0 | double |
Math.floor(x) | Largest integer ≤ x (down) | 2.0 | -3.0 | 2.0 | double |
Math.ceil(x) | Smallest integer ≥ x (up) | 3.0 | -2.0 | 3.0 | double |
(int) x (cast) | Drop the fraction (toward zero) | 2 | -2 | 2 | int |
Note that floor, ceil and rint return a double, and round returns a long. To store the result in an int you need a cast: int n = (int) Math.round(x);. Casts are covered in the next article.
Math.clamp(value, min, max) (Java 21) forces a value into a range: values below min become min, values above max become max, and values in range are unchanged. Before Java 21 you wrote Math.max(min, Math.min(max, value)).
Static imports: dropping the Math. prefix
If you use many Math methods, a static import at the top of the file lets you omit the class name:
import static java.lang.Math.*;
public class Geometry {
public static void main(String[] args) {
System.out.println("The square root of π is " + sqrt(PI));
}
}
Static imports are covered with packages in a later article. Use them sparingly: Math.sqrt tells the reader where sqrt comes from.
Overflow-Safe Integer Arithmetic
As you saw in the primitive-types article, integer operators silently overflow. One billion times three doesn't fit in an int:
public class Solution {
public static void main(String[] args) {
System.out.println(1_000_000_000 * 3);
try {
System.out.println(Math.multiplyExact(1_000_000_000, 3));
} catch (ArithmeticException e) {
System.out.println("multiplyExact: " + e.getMessage());
}
System.out.println(Math.multiplyExact(1_000_000_000L, 3));
System.out.println(Math.abs(Integer.MIN_VALUE));
}
}
-1294967296
multiplyExact: integer overflow
3000000000
-2147483648
The exact methods throw an ArithmeticException instead of returning a wrong answer, so the error can't go unnoticed:
| Method | Overflow-checked version of |
|---|---|
addExact(a, b) | a + b |
subtractExact(a, b) | a - b |
multiplyExact(a, b) | a * b |
incrementExact(a) / decrementExact(a) | a + 1 / a - 1 |
negateExact(a) | -a |
absExact(a) (Java 15+) | Math.abs(a) |
toIntExact(longValue) | (int) longValue |
divideExact(a, b) (Java 18+) | a / b (only overflows for MIN_VALUE / -1) |
All accept int or long arguments. The last line of the example shows another trap: Math.abs(Integer.MIN_VALUE) is still negative, because +2,147,483,648 doesn't fit in an int. Math.absExact would throw instead.
Math vs StrictMath
For speed, Math methods may use the processor's own floating-point instructions, which can differ in the last bit or so between platforms. If you need bit-for-bit identical results everywhere (some scientific and financial reproducibility requirements), use the StrictMath class instead. It has the same methods, implemented with a fixed, portable algorithm library (fdlibm, the "Freely Distributable Math Library").
Common questions
How does Math.round treat .5 values?
It rounds halves up, toward positive infinity: Math.round(2.5) is 3, and Math.round(-2.5) is -2. Math.rint(2.5) rounds halves to the nearest even number and gives 2.0. For money and other decimal rounding rules, use BigDecimal.setScale(2, RoundingMode.HALF_UP) or HALF_EVEN.
Is Math.pow(x, 2) slower than x * x?
Slightly, in principle, although the JIT often optimises common cases. More important: pow returns a double, so Math.pow(10, 2) is 100.0, not 100. For integer powers, use a loop, Math.multiplyExact, or BigInteger.pow.
What does Math.sqrt(-1) return?
NaN. Math methods don't throw exceptions for invalid floating-point input. They return NaN or infinity, as IEEE 754 requires. Check the result with Double.isNaN when bad input is possible.
Is there an integer square root or a modular power in Math?
No. For int and long values, (long) Math.sqrt(n) is accurate up to about 2⁵² but can be off by one for very large long values. BigInteger has sqrt() (Java 9) and modPow(...), which are exact for any size.
What is Math.fma?
Math.fma(a, b, c) (Java 9) computes a * b + c with a single rounding at the end instead of two. It is more accurate, and on modern CPUs often faster. Numerical code such as dot products and polynomials uses it.
Summary
+ - * / %are the arithmetic operators./on two integers performs integer division and discards the fraction; make one operand floating-point for real division.- Integer division by zero throws
ArithmeticException; floating-point division givesInfinityorNaN. %gives the remainder with the sign of the dividend:-15 % 2is-1. Test oddness withn % 2 != 0.Math.floorModgives a non-negative remainder for positive divisors (clocks, circular indexes);floorDivandceilDivround quotients down or up.- The
Mathclass suppliespow,sqrt,abs,max/min, rounding (round,floor,ceil,rint), trigonometry (radians), logarithms,clamp(21+), and the constantsPI,TAUandE. - Use
addExact,multiplyExactand friends when overflow must not go unnoticed;StrictMathwhen you need bit-identical results everywhere.
Practice Questions
What are the values of 17 / 5, 17 % 5, -17 / 5, -17 % 5 and 17.0 / 5?
3, 2, -3 (truncated toward zero), -2 (sign of the dividend), and 3.4.
Why is if (n % 2 == 1) a buggy oddness test, and what should you write?
For negative odd n, n % 2 is -1, so the test misses them. Write if (n % 2 != 0), or Math.floorMod(n, 2) == 1.
An array has 7 slots. index is the current position, and you step back 3 positions with wrap-around. Which expression gives the new index?
Math.floorMod(index - 3, 7). With index = 1, (1 - 3) % 7 is -2, an invalid index, while floorMod gives 5.
What do Math.round(-3.5), Math.floor(-3.5), Math.ceil(-3.5) and (int) -3.5 return?
Math.round(-3.5) → -3 (halves round toward positive infinity); Math.floor(-3.5) → -4.0; Math.ceil(-3.5) → -3.0; (int) -3.5 → -3 (fraction dropped toward zero).
Compute the hypotenuse of a right triangle with sides 5 and 12 in two different ways.
Math.sqrt(5 * 5 + 12 * 12) or Math.sqrt(Math.pow(5, 2) + Math.pow(12, 2)), or more simply Math.hypot(5, 12). All give 13.0. hypot also avoids intermediate overflow for huge values.
How many boxes of 12 eggs do you need for 100 eggs? Write it without floating-point arithmetic.
Math.ceilDiv(100, 12) → 9 (Java 18+). The classic formula is (100 + 12 - 1) / 12, which is also 9.
Previous: Java Variables, Constants, var and final Explained
Next: Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
Related reading
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents
- Java Streams Explained: From Loops to Stream Pipelines
- Your First Java Program Explained: Classes, main, Statements and Comments
- Java Variables, Constants, var and final Explained
- Java Keywords Reference: Every Keyword, Contextual Keyword and Literal

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.