Definition
Key method groups:
- Rounding:
round()(nearest integer),ceil()(up),floor()(down). - Min/Max/Abs:
min(a,b),max(a,b),abs(x). - Power/Root:
pow(base, exp),sqrt(n),cbrt(n). - Safe arithmetic:
addExact(),multiplyExact()– throw on overflow instead of wrapping. - Random:
Math.random()returns a double in [0.0, 1.0). - Constants:
Math.PI,Math.E.
The Math class is the bank's scientific calculator. It rounds interest calculations, finds the minimum payment, computes compound interest with pow(), and catches overflow errors when adding large account balances.
Understanding the Concepts
Rounding methods
System.out.println(Math.round(3.5)); // 4 (rounds half-up for positive)
System.out.println(Math.round(3.4)); // 3
System.out.println(Math.round(-3.5)); // -3 (rounds toward positive infinity)
System.out.println(Math.ceil(3.1)); // 4.0 (always up)
System.out.println(Math.floor(3.9)); // 3.0 (always down)
// For money: never use Math.round on double. Use BigDecimal rounding modes.
BigDecimal emi = principal.multiply(rate).setScale(2, RoundingMode.HALF_UP);
Min, Max, Abs
int fee = Math.max(minimumFee, calculatedFee); // at least minimumFee
int penalty = Math.min(maxPenalty, lateDays * dailyRate);
int distance = Math.abs(targetBalance - currentBalance);
Trap: Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE (negative!) because the positive value overflows int.
System.out.println(Math.abs(Integer.MIN_VALUE)); // -2147483648 (wrong!)
System.out.println(Math.absExact(Integer.MIN_VALUE)); // throws ArithmeticException (Java 15+)
Power and compound interest
// Compound interest: A = P * (1 + r/n)^(n*t)
double principal = 500000;
double rate = 0.085; // 8.5%
int years = 5;
double amount = principal * Math.pow(1 + rate, years);
System.out.println("After 5 years: " + amount); // ~751311.21
// For exact money: use BigDecimal
BigDecimal exact = new BigDecimal("500000")
.multiply(BigDecimal.ONE.add(new BigDecimal("0.085")).pow(5));
Safe overflow-checked arithmetic
try {
int result = Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow: " + e.getMessage()); // integer overflow
}
try {
long result = Math.multiplyExact(Long.MAX_VALUE, 2);
} catch (ArithmeticException e) {
System.out.println("Overflow: " + e.getMessage()); // long overflow
}
Use these in banking code where silent overflow could produce wrong monetary values.
Random numbers
// Math.random(): [0.0, 1.0)
double random = Math.random();
int otp = (int)(Math.random() * 900000) + 100000; // 6-digit OTP
// Better for multi-threaded: ThreadLocalRandom (no contention)
import java.util.concurrent.ThreadLocalRandom;
int otp2 = ThreadLocalRandom.current().nextInt(100000, 1000000);
// For security (OTP, tokens): SecureRandom
import java.security.SecureRandom;
int secureOtp = new SecureRandom().nextInt(100000, 1000000);
What are common mistakes?
- Math.abs(Integer.MIN_VALUE) is negative. Use
Math.absExact()(Java 15+) or cast to long first. - Using Math.round on double for money. Rounding errors compound. Use
BigDecimal.setScale(2, RoundingMode.HALF_UP). - Math.random() for security. Not cryptographically secure. Use
SecureRandomfor OTPs and tokens. - Ignoring overflow in addExact. Wrapping the call in try-catch is necessary – it throws, not returns a flag.
What should a senior engineer know?
- Math methods are JVM intrinsics.
Math.sqrt(),Math.min(), andMath.abs()are compiled to single CPU instructions by the JIT. Extremely fast. - StrictMath guarantees cross-platform results. Math may use platform-specific optimizations. Since Java 17,
strictfpis always enabled, so Math is also strict. - Math.fma() (Java 9+) performs fused multiply-add with one rounding instead of two. Important for scientific computing.
- Math.floorMod() handles negative dividends correctly:
Math.floorMod(-7, 3)is 2, not -1 like%.
Visual Overview
Math method groups:
Rounding: round(3.5)→4 ceil(3.1)→4.0 floor(3.9)→3.0
Min/Max: min(a,b) max(a,b)
Abs: abs(x) absExact(x) (Java 15+, throws on MIN_VALUE)
Power: pow(2,10)→1024 sqrt(144)→12.0
Safe arith: addExact(MAX,1)→throws multiplyExact(MAX,2)→throws
Random: random()→[0.0,1.0) ThreadLocalRandom SecureRandom
Constants: PI=3.14159... E=2.71828...
Money rule:
Math.round(double) → imprecise for money
BigDecimal.setScale(2, RoundingMode.HALF_UP) → exact
Key Takeaway
The Math class provides static utility methods for rounding, min/max, absolute value, power, safe arithmetic, and random numbers. It is in java.lang so no import is needed. Its methods are JVM intrinsics, compiled to single CPU instructions for maximum speed.
The key banking traps are: Math.abs(Integer.MIN_VALUE) returns a negative number due to overflow, Math.round on double is imprecise for money, and Math.random() is not cryptographically secure. Use Math.absExact() for safe absolute value, BigDecimal for money rounding, and SecureRandom for OTPs.
The most important methods for banking are Math.addExact() and Math.multiplyExact(), which throw ArithmeticException on overflow instead of wrapping silently. Use them whenever overflow in a calculation could produce a wrong monetary value.
One sentence to remember: Math provides fast numeric utilities, but use BigDecimal for money, absExact for safe abs, addExact for safe arithmetic, and SecureRandom for security.
---