Java Math

Su Suriya Ravichandran Updated 14 Nov 2026
5 min read ·Lesson 13 of 133

The java.lang.Math class provides static methods for common mathematical operations: rounding, powers, roots, absolute values, trigonometry, logarithms, and random numbers. It is in java.lang, so no import is needed, and every method is called on the class name: Math.sqrt(16).

Math cannot be instantiated. It is a utility class, a holder for functions, because these operations do not belong to any particular object.

Constants

System.out.println(Math.PI);   // 3.141592653589793
System.out.println(Math.E);    // 2.718281828459045

Both are double. Use them rather than typing approximations such as 3.14, which introduce avoidable error.

Minimum, Maximum, and Absolute Value

System.out.println(Math.max(7, 12));      // 12
System.out.println(Math.min(7, 12));      // 7
System.out.println(Math.max(2.5, -1.0));  // 2.5
System.out.println(Math.abs(-15));        // 15
System.out.println(Math.abs(-3.7));       // 3.7

These are overloaded for int, long, float, and double; the return type matches the argument type. Mixing types promotes to the wider one: Math.max(3, 4.5) returns 4.5 as a double.

To clamp a value into a range, combine them:

int volume = Math.max(0, Math.min(100, requested));   // keep within 0..100

Java 21 added Math.clamp(value, min, max) for exactly this purpose.

Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE (still negative), because its positive counterpart does not fit in an int. Math.absExact throws instead.

Powers and Roots

System.out.println(Math.pow(2, 10));   // 1024.0
System.out.println(Math.pow(9, 0.5));  // 3.0
System.out.println(Math.sqrt(144));    // 12.0
System.out.println(Math.cbrt(27));     // 3.0
System.out.println(Math.sqrt(-4));     // NaN

All return double. To store the result as an integer, cast it:

int area = (int) Math.pow(side, 2);

For squaring, side * side is faster and stays in integer arithmetic. Math.pow is for non-integer or variable exponents. Math.hypot(a, b) computes √(a² + b²) without intermediate overflow, useful for distances.

Rounding

Four methods round in different ways. The difference matters, especially with negative numbers.

MethodRule2.52.4-2.5-2.4
Math.round(x)Nearest; .5 goes up32-2-2
Math.ceil(x)Up, toward +∞3.03.0-2.0-2.0
Math.floor(x)Down, toward −∞2.02.0-3.0-3.0
Math.rint(x)Nearest; .5 goes to the even neighbor2.02.0-2.0-2.0
long r = Math.round(4.6);      // 5 (returns long for a double argument)
int r2 = Math.round(4.6f);     // 5 (returns int for a float argument)
double c = Math.ceil(4.1);     // 5.0
double f = Math.floor(4.9);    // 4.0

ceil and floor return double, not an integer type. round returns long for double input, so int x = Math.round(4.6); does not compile without a cast.

ceil is the standard tool for "how many containers are needed":

int items = 47, perPage = 10;
int pages = (int) Math.ceil((double) items / perPage);   // 5

The cast to double before dividing is essential; items / perPage in integer arithmetic is 4, and ceil(4) is still 4. An integer-only alternative is (items + perPage - 1) / perPage, or Math.ceilDiv(items, perPage) in Java 18+.

Rounding to decimal places

Math.round rounds to a whole number. To round to two decimals for display, format instead of computing:

double value = 3.14159;
System.out.printf("%.2f%n", value);            // 3.14
String s = String.format("%.2f", value);       // "3.14"

Computing Math.round(value * 100) / 100.0 works for display-level accuracy but can still produce binary artifacts. When the rounded value must be exact (financial calculations), use BigDecimal.setScale(2, RoundingMode.HALF_UP).

Exponential and Logarithmic Functions

System.out.println(Math.exp(1));       // 2.718281828459045 (e^1)
System.out.println(Math.log(Math.E));  // 1.0 (natural log)
System.out.println(Math.log10(1000));  // 3.0
System.out.println(Math.log(8) / Math.log(2));   // 3.0 (log base 2)

There is no direct log-base-2 method; dividing natural logarithms gives any base. Math.log of zero is -Infinity; of a negative number, NaN.

Trigonometry

Trigonometric methods work in radians, not degrees.

double deg = 30;
double rad = Math.toRadians(deg);
System.out.println(Math.sin(rad));            // 0.49999999999999994
System.out.println(Math.cos(Math.toRadians(60)));  // 0.5000000000000001
System.out.println(Math.toDegrees(Math.atan(1)));  // 45.0

Passing degrees directly is a common source of wrong results: Math.sin(30) is the sine of 30 radians (−0.988). The tiny errors in the output above are normal floating-point behavior; round when displaying.

Math.atan2(y, x) returns the angle of the point (x, y) from the origin, correctly handling all four quadrants, and is the usual choice for computing direction in games and graphics.

Random Numbers

Math.random() returns a double in the range [0.0, 1.0): zero inclusive, one exclusive.

double r = Math.random();                         // e.g. 0.7231...
int dice = (int) (Math.random() * 6) + 1;         // 1 to 6
int between = (int) (Math.random() * (max - min + 1)) + min;   // min..max inclusive

Multiplying by 6 scales the range to [0, 6); casting truncates to 0–5; adding 1 shifts to 1–6.

For more than occasional use, java.util.Random or ThreadLocalRandom is clearer and offers integer ranges directly:

import java.util.concurrent.ThreadLocalRandom;

int dice = ThreadLocalRandom.current().nextInt(1, 7);   // 1 to 6

Neither is suitable for security purposes such as tokens or passwords; use java.security.SecureRandom there. Random numbers are covered in a later lesson.

Exact Arithmetic

Normal int and long arithmetic wraps on overflow. The Exact methods throw ArithmeticException instead:

Math.addExact(Integer.MAX_VALUE, 1);        // throws
Math.multiplyExact(100_000, 100_000);       // throws: result exceeds int
Math.toIntExact(5_000_000_000L);            // throws: does not fit in int

Use them where a silent wrong answer would be worse than a crash: quantities, balances, array size calculations.

Floor Division and Modulus

Integer / and % truncate toward zero, which gives negative remainders for negative operands. floorDiv and floorMod round toward negative infinity instead, giving a remainder with the sign of the divisor:

System.out.println(-7 / 2);                // -3
System.out.println(Math.floorDiv(-7, 2));  // -4
System.out.println(-7 % 3);                // -1
System.out.println(Math.floorMod(-7, 3));  // 2

floorMod is the correct tool for wrapping a possibly negative value into a range, such as stepping backward through a circular list or converting a day offset into a day of the week.

Practical Example: Distance Between Two Coordinates

The haversine formula computes the great-circle distance between two points on Earth from their latitude and longitude:

public class Distance {
    static final double EARTH_RADIUS_KM = 6371.0;

    static double haversine(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

        double a = Math.pow(Math.sin(dLat / 2), 2)
                 + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                 * Math.pow(Math.sin(dLon / 2), 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return EARTH_RADIUS_KM * c;
    }

    public static void main(String[] args) {
        double km = haversine(13.0827, 80.2707, 12.9716, 77.5946);   // Chennai to Bengaluru
        System.out.printf("Distance: %.1f km%n", km);
    }
}

Output:

Distance: 290.2 km

The coordinates are in degrees, so every angle passes through Math.toRadians before reaching sin or cos. Math.pow(x, 2) squares the sines; Math.atan2 converts the intermediate value into the central angle; multiplying by Earth's radius gives the arc length. This is the same calculation used by delivery and ride-hailing apps to estimate straight-line distance before route planning.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about Java Math and get answers drawn from it.

Signed-in readers only.