-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Math Guide
Mattscreative edited this page Mar 9, 2026
·
1 revision
- Introduction
- Math Class Constants
- Basic Math Operations
- Rounding Operations
- Trigonometric Functions
- Power and Logarithms
- Random Numbers
- Number Utilities
- BigInteger and BigDecimal
- Practical Examples
Java provides the Math class (in java.lang package) for mathematical operations. No import needed - it's automatically available!
// Basic constants
System.out.println(Math.PI); // 3.141592653589793 (π)
System.out.println(Math.E); // 2.718281828459045 (e)
// Using in calculations
double circleArea = Math.PI * radius * radius;
double compoundInterest = principal * Math.pow(1 + rate, time);// Absolute value
Math.abs(-5); // 5
Math.abs(5); // 5
Math.abs(-3.14); // 3.14
// Maximum and minimum
Math.max(5, 10); // 10
Math.min(5, 10); // 5
Math.max(3, Math.max(7, 2)); // 7 (chained)
// Find max/min in arrays
int[] numbers = {5, 2, 8, 1, 9};
int max = Arrays.stream(numbers).max().orElse(0); // 9
int min = Arrays.stream(numbers).min().orElse(0); // 1
// Square root
Math.sqrt(16); // 4.0
Math.sqrt(2); // 1.414213562...
// Cube root
Math.cbrt(27); // 3.0
Math.cbrt(-8); // -2.0// Round to nearest integer
Math.round(3.7); // 4 (returns long)
Math.round(3.2); // 3
Math.round(-3.7); // -4
// Floor (round down)
Math.floor(3.9); // 3.0
Math.floor(-3.1); // -4.0
// Ceiling (round up)
Math.ceil(3.1); // 4.0
Math.ceil(-3.9); // -3.0
// Rint (round to nearest integer)
Math.rint(3.5); // 4.0 (rounds to even)
Math.rint(3.4); // 3.0
Math.rint(4.5); // 4.0
// Custom rounding to decimal places
double num = 3.14159;
// Round to 2 decimal places
double rounded = Math.round(num * 100.0) / 100.0; // 3.14
// Using BigDecimal for precise rounding
import java.math.BigDecimal;
import java.math.RoundingMode;
BigDecimal bd = new BigDecimal("3.14159");
bd = bd.setScale(2, RoundingMode.HALF_UP); // 3.14// All angles are in RADIANS!
// Convert degrees to radians
double radians = Math.toRadians(45); // 0.785398...
// Convert radians to degrees
double degrees = Math.toDegrees(Math.PI); // 180.0
// Sine, cosine, tangent
Math.sin(Math.PI / 2); // 1.0 (sin of 90°)
Math.cos(0); // 1.0 (cos of 0°)
Math.tan(Math.PI / 4); // 1.0 (tan of 45°)
// Inverse trig functions
Math.asin(1); // π/2 (arc sine)
Math.acos(1); // 0 (arc cosine)
Math.atan(1); // π/4 (arc tangent)
// Hyperbolic functions
Math.sinh(1); // Hyperbolic sine
Math.cosh(1); // Hyperbolic cosine
Math.tanh(1); // Hyperbolic tangent// Calculate coordinates on a circle
double radius = 10;
double angle = Math.toRadians(45); // 45 degrees
double x = radius * Math.cos(angle);
double y = radius * Math.sin(angle);
System.out.println("X: " + x); // ~7.07
System.out.println("Y: " + y); // ~7.07// Power operations
Math.pow(2, 3); // 8.0 (2³)
Math.pow(4, 0.5); // 2.0 (√4)
Math.pow(2, -1); // 0.5 (2⁻¹)
// Exponential
Math.exp(1); // e¹ ≈ 2.718
Math.exp(2); // e² ≈ 7.389
// Natural logarithm (base e)
Math.log(Math.E); // 1.0
Math.log(10); // ~2.303
// Logarithm base 10
Math.log10(100); // 2.0
Math.log10(1000); // 3.0
// Logarithm base 2
Math.log2(8); // 3.0
// Log of any base
double logBase5 = Math.log(125) / Math.log(5); // 3.0// Random double between 0.0 (inclusive) and 1.0 (exclusive)
double random = Math.random(); // 0.0 to 0.999...
// Random between 0 and 100
int num = (int) (Math.random() * 101); // 0 to 100
// Random between 1 and 100
int num2 = (int) (Math.random() * 100) + 1; // 1 to 100
// Random between min and max
int min = 5, max = 10;
int num3 = (int) (Math.random() * (max - min + 1)) + min; // 5 to 10import java.util.Random;
Random rand = new Random();
// Random integers
int nextInt = rand.nextInt(); // Any integer
int boundInt = rand.nextInt(10); // 0 to 9
// Random with range
int rangedInt = rand.nextInt(100) + 1; // 1 to 100
// Random long
long nextLong = rand.nextLong();
// Random boolean
boolean nextBool = rand.nextDouble() > 0.5;
// Random doubles
double nextDouble = rand.nextDouble(); // 0.0 to 1.0
// Gaussian (normal distribution)
double gaussian = rand.nextGaussian(); // Mean 0, std dev 1import java.util.concurrent.ThreadLocalRandom;
// For multi-threaded applications
int randomInt = ThreadLocalRandom.current().nextInt(1, 101); // 1-100
double randomDouble = ThreadLocalRandom.current().nextDouble();import java.security.SecureRandom;
SecureRandom secRand = new SecureRandom();
int secureInt = secRand.nextInt();
byte[] bytes = new byte[16];
secRand.nextBytes(bytes); // Fill with random bytes// Check if number is even/odd
boolean isEven = (num % 2 == 0);
boolean isOdd = (num % 2 != 0);
// Factorial
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// Power without Math.pow
int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}
// Check if prime
boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}// Check for NaN and Infinity
Double.isNaN(0.0 / 0.0); // true (NaN)
Double.isInfinite(1.0 / 0.0); // true (Infinity)
Double.isFinite(1.0); // true (Java 8+)
// Compare with epsilon
boolean approxEqual(double a, double b) {
double epsilon = 0.0001;
return Math.abs(a - b) < epsilon;
}import java.math.BigInteger;
BigInteger big = new BigInteger("12345678901234567890");
BigInteger big2 = new BigInteger("98765432109876543210");
// Operations
BigInteger sum = big.add(big2); // Addition
BigInteger diff = big.subtract(big2); // Subtraction
BigInteger prod = big.multiply(big2); // Multiplication
BigInteger quot = big.divide(big2); // Division
BigInteger rem = big.mod(big2); // Remainder
// Convert
int intVal = big.intValue();
long longVal = big.longValue();
String strVal = big.toString();
// Factorial with BigInteger
BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}import java.math.BigDecimal;
import java.math.RoundingMode;
BigDecimal bd = new BigDecimal("3.14159");
BigDecimal bd2 = new BigDecimal("2.5");
// Operations
BigDecimal sum = bd.add(bd2);
BigDecimal diff = bd.subtract(bd2);
BigDecimal prod = bd.multiply(bd2);
BigDecimal quot = bd.divide(bd2, 10, RoundingMode.HALF_UP);
// Scale operations
BigDecimal scaled = bd.setScale(2, RoundingMode.HALF_UP); // 3.14
BigDecimal stripped = bd.stripTrailingZeros(); // Remove trailing zeros
// Compare (equals considers scale!)
bd.equals(bd2); // false
bd.compareTo(bd2) == 0; // Compare values (0 if equal)
// Financial calculations
BigDecimal price = new BigDecimal("19.99");
BigDecimal taxRate = new BigDecimal("0.0825");
BigDecimal tax = price.multiply(taxRate).setScale(2, RoundingMode.HALF_UP);
BigDecimal total = price.add(tax);class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
double distanceTo(Point other) {
double dx = other.x - this.x;
double dy = other.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
// Usage
Point p1 = new Point(0, 0);
Point p2 = new Point(3, 4);
System.out.println(p1.distanceTo(p2)); // 5.0 (3-4-5 triangle!)import java.math.BigDecimal;
import java.math.RoundingMode;
class LoanCalculator {
public static BigDecimal calculatePayment(
BigDecimal principal,
BigDecimal annualRate,
int years) {
// Monthly rate
BigDecimal monthlyRate = annualRate.divide(
BigDecimal.valueOf(12),
10,
RoundingMode.HALF_UP
);
// Number of payments
int payments = years * 12;
// Calculate: P * [r(1+r)^n] / [(1+r)^n - 1]
BigDecimal one = BigDecimal.ONE;
BigDecimal onePlusR = one.add(monthlyRate);
BigDecimal numerator = monthlyRate.multiply(onePlusR.pow(payments));
BigDecimal denominator = onePlusR.pow(payments).subtract(one);
BigDecimal payment = principal.multiply(numerator.divide(
denominator,
2,
RoundingMode.HALF_UP
));
return payment.setScale(2, RoundingMode.HALF_UP);
}
public static void main(String[] args) {
BigDecimal principal = new BigDecimal("250000");
BigDecimal rate = new BigDecimal("0.065"); // 6.5%
BigDecimal payment = calculatePayment(principal, rate, 30);
System.out.println("Monthly payment: $" + payment);
}
}import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
class Statistics {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
// Using IntStream for statistics
IntSummaryStatistics stats = Arrays.stream(numbers).summaryStatistics();
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Average: " + stats.getAverage());
// Standard deviation
double mean = stats.getAverage();
double stdDev = Math.sqrt(
Arrays.stream(numbers)
.mapToDouble(x -> Math.pow(x - mean, 2))
.sum() / stats.getCount()
);
System.out.println("Std Dev: " + stdDev);
// Median
Arrays.sort(numbers);
int mid = numbers.length / 2;
double median = (numbers.length % 2 == 0)
? (numbers[mid - 1] + numbers[mid]) / 2.0
: numbers[mid];
System.out.println("Median: " + median);
}
}In this guide, you learned:
- ✅ Math class constants (PI, E)
- ✅ Basic math operations (abs, max, min, sqrt)
- ✅ Rounding operations (floor, ceil, round)
- ✅ Trigonometric functions (sin, cos, tan)
- ✅ Power and logarithms (pow, exp, log)
- ✅ Random number generation (multiple methods)
- ✅ Number utilities
- ✅ BigInteger and BigDecimal for precision
- Java Beginner Guide - Part 1 - Fundamentals
- Java Complete Reference - Quick Reference
- Java Advanced Guide - Collections and Streams
Master the Math class and make your calculations precise! 🧮