Java Math API, BigInteger and BigDecimal (OCP 21)
The java.lang.Math methods on the OCP Java 21 exam with their exact return types: min, max, round, ceil, floor, pow, random, plus abs, sqrt, Java 21's clamp, floorDiv/floorMod and exact arithmetic, and BigInteger and BigDecimal for big or exact numbers.
kvi5hnuCode Sprout team member7 min readOn this page
java.lang.Math is a utility class full of static methods. You never create a Math object, and since it's in java.lang, it needs no import. The exam questions are rarely about the math itself. They're about return types: Math.round(2.5) returns a long, Math.ceil returns a double, and assigning either to an int doesn't compile. This article covers the methods you need to know, a few newer ones worth recognizing, and BigInteger and BigDecimal for numbers that primitives can't hold exactly.
min and max
static int min(int a, int b) static int max(int a, int b)
static long min(long a, long b) static long max(long a, long b)
static float min(float a, float b) static float max(float a, float b)
static double min(double a, double b) static double max(double a, double b)
Overload resolution picks the narrowest version that fits both arguments, so the result type follows the wider argument:
Math.max(3, 7); // 7 (int)
Math.min(7, -9); // -9 (int)
Math.max(3, 7.0); // 7.0 (double: 3 is widened)
int bad = Math.max(1, 2L); // DOES NOT COMPILE: the long version returns long
Rounding: round, ceil, floor
| Method | Parameter → return | Rule |
|---|---|---|
Math.round(double) | double → long | Nearest whole number. A tie (.5) goes up, toward positive infinity |
Math.round(float) | float → int | Same rule |
Math.ceil(double) | double → double | Smallest whole number ≥ the value |
Math.floor(double) | double → double | Largest whole number ≤ the value |
cast (int) d | — | Drops the fraction, toward zero (not a Math method) |

long low = Math.round(123.45); // 123
long high = Math.round(123.5); // 124
int f = Math.round(123.45f); // 123: the float version returns int
Math.round(-2.5); // -2 (ties go toward +infinity)
Math.round(-2.51); // -3
Math.ceil(3.14); // 4.0
Math.floor(-3.14); // -4.0
Math.ceil(5); // 5.0: the int is widened to double
On the exam, the trap is usually the assignment, not the arithmetic. int r = Math.round(2.5); doesn't compile (long to int), and neither does int c = Math.ceil(2.1); (double to int).
Powers, roots, absolute values
static double pow(double base, double exponent)
static double sqrt(double a)
static int abs(int a) // also long, float, double
Math.pow(5, 2); // 25.0: always a double
Math.pow(16, 0.5); // 4.0
Math.pow(2, -2); // 0.25
Math.sqrt(81); // 9.0
Math.sqrt(-1); // NaN, no exception
Math.abs(-12); // 12
Math.abs(Integer.MIN_VALUE); // -2147483648: its positive value doesn't fit in an int
int p = Math.pow(2, 3); doesn't compile. Cast the result, or keep it as a double.
random
static double random() // 0.0 <= result < 1.0
It never returns 1.0 and never a negative number. To get a whole number from 1 to 6, use (int) (Math.random() * 6) + 1. In real code, prefer ThreadLocalRandom.current().nextInt(1, 7) or the RandomGenerator API (Java 17).
Newer Math methods worth recognizing
These aren't the focus of the exam's Math questions, but they appear in modern code, and some are new in Java 21:
| Method | Since | Purpose |
|---|---|---|
Math.clamp(value, min, max) | Java 21 | Limits value to [min, max]: clamp(15, 0, 10) is 10. Throws IllegalArgumentException if min > max |
floorDiv(a, b), floorMod(a, b) | 8 | Division and remainder rounded toward negative infinity: floorDiv(-7, 2) is -4 while -7 / 2 is -3, and floorMod(-7, 2) is 1 while -7 % 2 is -1 |
addExact, multiplyExact, toIntExact… | 8 | Throw ArithmeticException on overflow instead of silently wrapping |
ceilDiv, ceilMod | 18 | Division rounded toward positive infinity |
Integer.MAX_VALUE + 1 silently wraps to -2147483648. Math.addExact(Integer.MAX_VALUE, 1) throws ArithmeticException: integer overflow. When overflow would be a bug, use the …Exact methods.
BigInteger and BigDecimal
Primitive numbers have two limits: range (a long stops at about 9.2 × 10¹⁸) and precision (a double can't represent most decimal fractions exactly). The classes in java.math remove both limits:
BigInteger: whole numbers of any size;BigDecimal: decimal numbers with exact digits and a chosen scale (the number of digits after the point).
Both are immutable, like String. Every operation returns a new object, so you chain calls or reassign the result:
BigDecimal ten = BigDecimal.TEN;
ten.add(BigDecimal.ONE); // result discarded
System.out.println(ten); // 10
Creating them
BigInteger.valueOf(5_000L); // from a long
new BigInteger("98765432109876543210"); // from a String: any size
BigDecimal.valueOf(5_000L); // 5000
BigDecimal.valueOf(5_000.00); // 5000.0: from a double, via Double.toString
new BigDecimal("19.99"); // exactly 19.99
new BigDecimal(0.1); // 0.1000000000000000055511151231257827… (avoid!)
BigInteger.valueOftakes alongonly.BigInteger.valueOf(2.5)doesn't compile.BigDecimal.valueOf(double)goes through the double's shortest decimal text, sovalueOf(0.1)is0.1. Thenew BigDecimal(double)constructor captures the binary value exactly, errors included. UsevalueOfor theStringconstructor.- Common constants:
BigInteger.ZERO,ONE,TWO(Java 9),TEN, andBigDecimal.ZERO,ONE,TWO(Java 19),TEN.
Doing arithmetic
Operators don't work on objects, so arithmetic uses methods, and their arguments must be the same big type:
BigInteger r = BigInteger.valueOf(149).add(BigInteger.ONE) // 150
.divide(BigInteger.TEN) // 15
.max(BigInteger.valueOf(12)); // 15
BigInteger.valueOf(5).add(5); // DOES NOT COMPILE: add takes a BigInteger
Typical methods: add, subtract, multiply, divide, remainder/mod, pow, negate, abs, min, max, compareTo, and conversions such as intValue() or longValueExact().
Why money uses BigDecimal
System.out.println(4.35 * 100); // 434.99999999999994
System.out.println(BigDecimal.valueOf(4.35).multiply(BigDecimal.valueOf(100))); // 435.00
The double result is off because 4.35 has no exact binary representation. BigDecimal keeps decimal digits exactly. Its result has scale 2, because the scale of a product is the sum of the operands' scales (2 + 0).
Division and rounding
divide with a result that has no finite decimal expansion throws:
BigDecimal.ONE.divide(BigDecimal.valueOf(3));
// ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
BigDecimal.ONE.divide(BigDecimal.valueOf(3), 4, RoundingMode.HALF_UP); // 0.3333
new BigDecimal("4.947525").setScale(2, RoundingMode.HALF_UP); // 4.95
Always say how to round, with a scale and a RoundingMode (HALF_UP, HALF_EVEN for banker's rounding, DOWN, CEILING…) or a MathContext.
equals versus compareTo
BigDecimal.equals compares the value and the scale. compareTo compares only the numeric value:
new BigDecimal("2.0").equals(new BigDecimal("2.00")); // false (scale 1 vs 2)
new BigDecimal("2.0").compareTo(new BigDecimal("2.00")); // 0
Compare amounts with compareTo(...) == 0. This is also why a HashSet<BigDecimal> can hold both 2.0 and 2.00.
What's current
Math.clampwas added in Java 21, so it can appear on 1Z0-830.- Java 25 added
Math.powExactandunsignedPowExact(an exact integer power that throwsArithmeticExceptionon overflow), plusunsignedMultiplyExact. They aren't on 1Z0-830. BigIntegerandBigDecimaldidn't change in Java 22 through 25. TheBigDecimal(double)constructor still captures the exact binary value. PreferBigDecimal.valueOf(double)or theStringconstructor.
Exam traps from this article
A complete example
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
public class Solution {
// Money in BigDecimal: exact decimal arithmetic, explicit rounding
static BigDecimal totalWithTax(BigDecimal unitPrice, int quantity, String taxRate) {
BigDecimal net = unitPrice.multiply(BigDecimal.valueOf(quantity));
BigDecimal tax = net.multiply(new BigDecimal(taxRate)).setScale(2, RoundingMode.HALF_UP);
return net.add(tax);
}
public static void main(String[] args) {
System.out.println("-- min, max, abs, clamp --");
System.out.println(Math.max(3, 7) + " " + Math.min(7, -9) + " " + Math.max(3, 7.0)
+ " " + Math.abs(-12) + " " + Math.abs(Integer.MIN_VALUE));
System.out.println(Math.clamp(15, 0, 10) + " " + Math.clamp(-3, 0, 10) + " "
+ Math.clamp(0.75, 0.0, 0.5)); // Java 21
System.out.println("-- rounding --");
System.out.println(Math.round(123.45) + " " + Math.round(123.5) + " " + Math.round(123.45f)
+ " " + Math.round(-2.5) + " " + Math.round(-2.51));
System.out.println(Math.ceil(3.14) + " " + Math.floor(3.14) + " " + Math.ceil(-3.14)
+ " " + Math.floor(-3.14) + " " + (int) -3.99);
System.out.println("-- powers and roots --");
System.out.println(Math.pow(5, 2) + " " + Math.pow(16, 0.5) + " " + Math.pow(2, -2)
+ " " + Math.sqrt(81) + " " + Math.sqrt(-1));
System.out.println("-- division that rounds toward negative infinity --");
System.out.println((-7 / 2) + " " + Math.floorDiv(-7, 2) + " " + (-7 % 2) + " " + Math.floorMod(-7, 2));
System.out.println("-- overflow: silent vs. exact --");
System.out.println(Integer.MAX_VALUE + 1);
try {
Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.println("addExact: " + e.getMessage());
}
System.out.println("-- random --");
int roll = (int) (Math.random() * 6) + 1;
System.out.println("die roll in range 1..6: " + (roll >= 1 && roll <= 6));
System.out.println("-- BigInteger --");
BigInteger result = BigInteger.valueOf(149).add(BigInteger.ONE)
.divide(BigInteger.TEN).max(BigInteger.valueOf(12));
System.out.println(result + " " + BigInteger.TWO.pow(70) + " "
+ new BigInteger("98765432109876543210").mod(BigInteger.valueOf(97)));
System.out.println("-- BigDecimal --");
System.out.println(4.35 * 100 + " vs " + BigDecimal.valueOf(4.35).multiply(BigDecimal.valueOf(100)));
System.out.println(new BigDecimal(0.1) + " vs " + new BigDecimal("0.1"));
BigDecimal two = new BigDecimal("2.0");
BigDecimal twoAgain = new BigDecimal("2.00");
System.out.println("equals " + two.equals(twoAgain) + ", compareTo " + two.compareTo(twoAgain));
BigDecimal ten = BigDecimal.TEN;
ten.add(BigDecimal.ONE); // result discarded: immutable
System.out.println("still " + ten);
try {
BigDecimal.ONE.divide(BigDecimal.valueOf(3));
} catch (ArithmeticException e) {
System.out.println("1/3: " + e.getMessage());
}
System.out.println(BigDecimal.ONE.divide(BigDecimal.valueOf(3), 4, RoundingMode.HALF_UP));
System.out.println("order total: " + totalWithTax(new BigDecimal("19.99"), 3, "0.0825"));
}
}
Output:
-- min, max, abs, clamp --
7 -9 7.0 12 -2147483648
10 0 0.5
-- rounding --
123 124 123 -2 -3
4.0 3.0 -3.0 -4.0 -3
-- powers and roots --
25.0 4.0 0.25 9.0 NaN
-- division that rounds toward negative infinity --
-3 -4 -1 1
-- overflow: silent vs. exact --
-2147483648
addExact: integer overflow
-- random --
die roll in range 1..6: true
-- BigInteger --
15 1180591620717411303424 62
-- BigDecimal --
434.99999999999994 vs 435.00
0.1000000000000000055511151231257827021181583404541015625 vs 0.1
equals false, compareTo 0
still 10
1/3: Non-terminating decimal expansion; no exact representable decimal result.
0.3333
order total: 64.92
Points to notice:
Math.max(3, 7.0)prints7.0: thedoubleoverload was chosen.Math.clamp(Java 21) hasint,long,floatanddoubleversions. One overload takes alongvalue withintbounds and returns anint, which makes it a safe way to narrow.Math.round(123.45f)uses thefloatoverload, which returns anint.floorDiv/floorModdiffer from/and%only for negative operands.new BigDecimal(0.1)shows the binary error thatBigDecimal.valueOfand theStringconstructor avoid.- The order total uses
setScale(2, HALF_UP)on the tax before adding, which is the normal way to handle money.
Common questions
Why does Math.round return a long for a double?
A double can hold values far larger than Integer.MAX_VALUE, so the rounded result needs a long. A float's precision is closer to int's, so its overload returns an int.
Is Math.round the same as RoundingMode.HALF_UP?
Not for negative numbers. Math.round returns the closest whole number and sends ties toward positive infinity (roughly floor(x + 0.5)), so round(-2.5) is -2. HALF_UP sends ties away from zero, so -2.5 becomes -3.
Should I use float or double for money?
Neither. Use BigDecimal with an explicit scale and rounding mode, or store whole cents in a long.
What's StrictMath?
It has the same methods with bit-for-bit identical results on every platform. Since Java 17 (JEP 306), all floating-point arithmetic is strict anyway, so the difference matters less than it used to.
Summary
Math.min/maxhaveint,long,floatanddoubleoverloads, and the result type follows the wider argument.round(double)→longandround(float)→int, with ties going toward positive infinity.ceil,floor,powandsqrtreturndouble.random()returns[0.0, 1.0). Java 21 addedclamp. Use the…Exactmethods when overflow must not go unnoticed.BigIntegerandBigDecimalare immutable and support any size. Create them withvalueOfor theStringconstructor, and use method calls for arithmetic.BigDecimaldivision needs a scale and rounding mode when the result doesn't terminate.equalschecks the scale, whilecompareTodoesn't.
Practice quiz
Test yourself with the Math, BigInteger and BigDecimal quiz: 10 exam-style questions with explanations.
Previous: Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
Next: Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
Related reading
- Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
- Java Arrays: Creating, Sorting and Searching (OCP 21)
- Java String Equality: ==, equals, the String Pool and intern (OCP 21)
- Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
- Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.