iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Math

Java math: java.lang.Math, BigDecimal for money, java.math.BigInteger, and the gotchas around int overflow + float precision.

Java — math

EXAMPLE
// ===== java.lang.Math (static methods) =====
Math.abs(-5);            // 5
Math.min(2, 7);          // 2
Math.max(2, 7);          // 7
Math.pow(2, 10);         // 1024.0
Math.sqrt(2);            // 1.4142...
Math.floor(3.7);         // 3.0
Math.ceil(3.2);          // 4.0
Math.round(3.5);         // 4 (long)

Math.PI; Math.E;

// Trig + log:
Math.sin(Math.PI / 2);   // 1.0
Math.cos(0);             // 1.0
Math.log(Math.E);        // 1.0
Math.log10(1000);        // 3.0

// Random:
Math.random();           // [0.0, 1.0)
new java.util.Random().nextInt(100);   // [0, 100)
new java.util.SplittableRandom().nextDouble();

// For CSPRNG: java.security.SecureRandom

// ===== Int overflow =====
int x = Integer.MAX_VALUE;    // 2_147_483_647
x = x + 1;                    // -2_147_483_648 (silent wrap!)

// Use Math.addExact, multiplyExact for checked arithmetic:
try {
    int n = Math.addExact(x, 1);
} catch (ArithmeticException e) {
    System.out.println("overflow");
}

// ===== Floats are not exact =====
0.1 + 0.2;                // 0.30000000000000004
double sum = 0.0;
for (int i = 0; i < 10; i++) sum += 0.1;
// sum = 0.9999999999999999

// ===== BigDecimal for money =====
import java.math.BigDecimal;
import java.math.RoundingMode;

BigDecimal price = new BigDecimal("49.95");
BigDecimal tax   = new BigDecimal("0.10");
BigDecimal total = price.multiply(BigDecimal.ONE.add(tax))
                        .setScale(2, RoundingMode.HALF_UP);
// 54.95

// Use string constructor; the double constructor can introduce float artefacts.

// BigDecimal arithmetic:
BigDecimal sum2 = price.add(price);
BigDecimal diff = price.subtract(tax);
BigDecimal div  = price.divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP);

// Compare with compareTo, NOT equals:
//   new BigDecimal("2.0").equals(new BigDecimal("2.00"))  -> false (scale differs)
//   .compareTo == 0 is the right check.

// ===== BigInteger for arbitrary precision =====
import java.math.BigInteger;
BigInteger a = new BigInteger("123456789012345678901234567890");
BigInteger b = BigInteger.TWO.pow(100);
BigInteger c = a.multiply(b);

// ===== Type conversions =====
int i = 5;
long l = i;                    // implicit widening
double d = i;                  // implicit widening
int back = (int) 3.99;         // explicit narrowing; truncates to 3
long bigL = 4_000_000_000L;    // L suffix
float fl = 1.0f;               // f suffix

// ===== Integer parsing =====
Integer.parseInt("42");
Integer.parseInt("FF", 16);    // 255 (base 16)
Long.parseLong("4000000000");
Double.parseDouble("3.14");

// ===== Patterns to internalise =====
// - BigDecimal for money; always use the String constructor
// - Math.*Exact when overflow matters
// - SecureRandom for security; Random for games / simulations
// - .compareTo on BigDecimal, not .equals

// ===== Pitfalls =====
// - 0.1 + 0.2 != 0.3 in double; use BigDecimal where it matters
// - Silent integer overflow wrapping
// - new BigDecimal(0.1) -> introduces double precision artefacts
// - Math.round on a double > Integer.MAX_VALUE clamps silently

Why it matters

Math in Java: java.lang.Math for primitives, BigDecimal for money, BigInteger for arbitrary precision. Math.*Exact catches overflow; SecureRandom for security; .compareTo on BigDecimal. Double for science, decimal for money — get the boundary right and the surprises stop.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
System.out.println(Math.max(7, 3));
System.out.println(Math.sqrt(16));
System.out.println(Math.PI);
Try it Yourself »

Discussion

Loading…