Java Math Class

Beginner
9 min read
Updated: Nov 2026
3 examples
java.lang.Math

Definition and Usage

In Java, java.lang.Math is a built-in class of static methods for number work: rounding, powers and roots, logarithms, trigonometry, random numbers, and integer arithmetic that detects overflow. The class is final with a private constructor and lives in java.lang, so you never import it and never write new Math(). You just call Math.sqrt(2.0).

It also has two constants: Math.PI (3.141592653589793) and Math.E (2.718281828459045), the base of natural logarithms. Popular methods include abs(), round(), pow(), sqrt(), max(), and random(). The Math Methods index lists every guide.

Math vs StrictMath.

StrictMath has the same methods but always uses one fixed set of algorithms, so results are identical on every machine. Math may use faster processor-specific code for sin, exp, pow, and similar functions, so their last digit can differ between platforms. abs, sqrt, floor, and round are exact either way.

Java Syntax

Write the class name, a dot, and the method. No import needed:

Java
double hyp = Math.sqrt(3 * 3 + 4 * 4);   // 5.0
double cube = Math.pow(2, 3);            // 8.0
int smaller = Math.min(-3, 8);           // -3
long nearest = Math.round(7.5);          // 8
double tau = 2 * Math.PI;                // 6.283185307179586

Types and Overloads: double, float, int, long

Most methods work only on double. A few have one version per type, picked from your arguments:

MethodsOverloadsExample
abs, max, minint, long, float, doubleMath.max(3, 9) is 9; Math.max(3, 9.0) is 9.0
roundfloat to int, double to longMath.round(2.5f) is an int
addExact and other *Exactint, longMath.addExact(5L, 7L) is the long 12
sqrt, pow, sin, ...double onlyMath.sqrt(9) returns 3.0

Special Values: NaN, Infinity, and -0.0

Double math never throws. Impossible results become special values that flow through later calls:

ExpressionResultWhy
Math.sqrt(-1)NaNNo real root; NaN means "not a number"
Math.log(0)-InfinityThe logarithm has no lower limit
1.0 / 0InfinityDouble division by zero does not throw
Math.min(-0.0, 0.0)-0.0Doubles have a negative zero

NaN is not equal even to itself, so test it with Double.isNaN(x).

Integer Overflow and the Exact Methods

An int holds -2147483648 to 2147483647. When +, -, or * goes past that range, Java wraps around silently: Integer.MAX_VALUE + 1 is -2147483648. The *Exact methods, such as addExact() and multiplyExact(), throw ArithmeticException instead of returning a wrong number. Even Math.abs(Integer.MIN_VALUE) is still negative.

The Rounding Family

ceil() rounds up, floor() rounds down, rint() rounds to nearest with .5 ties to even, and round() rounds to nearest with ties toward positive infinity. The first three return a double; round returns a long (an int for a float). For money, prefer whole cents in a long or java.math.BigDecimal: 0.1 + 0.2 prints 0.30000000000000004.

Degrees vs Radians

sin(), cos(), and tan() expect radians, and the inverse functions return radians. A full circle is 360 degrees or 2 * pi radians. Convert with toRadians() and toDegrees(): Math.sin(30) uses 30 radians; Math.sin(Math.toRadians(30)) uses 30 degrees and gives about 0.5.

Math.random() vs java.util.Random

random() returns a double from 0.0 up to, but never including, 1.0, handy for a quick dice roll: (int) (Math.random() * 6) + 1. For a repeatable sequence (a seed) or many threads, use a java.util.Random object or ThreadLocalRandom.current().

Java Examples

Example 1 — Circle Area, Rounding, Roots, and Extremes

The most common calls: Math.PI, a power, rounding to cents, a root, a maximum, and an absolute value.

Java
public class MathHubBasics {
    public static void main(String[] args) {
        double radius = 3.0;
        double area = Math.PI * Math.pow(radius, 2);
        System.out.println("Area: " + area);
        System.out.println("Rounded: " + Math.round(area * 100) / 100.0);
        System.out.println("sqrt(16) = " + Math.sqrt(16));
        System.out.println("max(7, 12) = " + Math.max(7, 12));
        System.out.println("abs(-4.5) = " + Math.abs(-4.5));
    }
}

How It Works

  1. Constant times a power. Math.pow(3.0, 2) is exactly 9.0; times Math.PI it prints the full double 28.274333882308138.
  2. Two decimals for people. Math.round(area * 100) gives the long 2827, and dividing by 100.0 gives 28.27.
  3. Result types follow the overload. sqrt returns a double (4.0), while max(7, 12) uses the int overload and prints 12.

Example 2 — Silent Overflow vs addExact, and floorMod vs %

Plain int arithmetic wraps around without warning; addExact throws instead. floorMod gives a remainder that is never negative for a positive divisor.

Java
public class MathHubOverflow {
    public static void main(String[] args) {
        int big = Integer.MAX_VALUE;
        System.out.println("big + 1 = " + (big + 1));
        try {
            Math.addExact(big, 1);
        } catch (ArithmeticException e) {
            System.out.println("addExact: " + e.getMessage());
        }
        System.out.println("floorMod(-7, 3) = " + Math.floorMod(-7, 3) + ", -7 % 3 = " + (-7 % 3));
    }
}

How It Works

  1. Wrap-around. 2147483647 is the largest int; adding 1 with + silently wraps to -2147483648.
  2. Fail loudly instead. Math.addExact detects the same overflow and throws ArithmeticException ("integer overflow").
  3. Two kinds of remainder. -7 % 3 keeps the sign of -7 and gives -1, while Math.floorMod(-7, 3) follows the divisor 3 and gives 2.

Example 3 — The Rounding Family and Degrees vs Radians

Compare the four rounding methods on the same values, then take the sine of 30 degrees.

Java
public class MathHubRounding {
    public static void main(String[] args) {
        double[] values = {2.5, -2.5, 3.7};
        for (double v : values) {
            System.out.println(v + ": ceil " + Math.ceil(v) + ", floor " + Math.floor(v)
                    + ", rint " + Math.rint(v) + ", round " + Math.round(v));
        }
        double s = Math.sin(Math.toRadians(30));
        System.out.println("sin(30 deg) = " + s);
        System.out.println("rounded = " + Math.round(s * 100) / 100.0);
    }
}

How It Works

  1. Up, down, even, half-up. rint sends a .5 tie to the even neighbour (2.5 to 2.0); round sends it toward positive infinity (2.5 to 3, -2.5 to -2).
  2. double vs long results. ceil, floor, and rint return doubles such as 3.0; Math.round(double) returns a long and prints 3.
  3. Radians in, tiny error out. Math.toRadians(30) is only close to pi/6, so the sine prints 0.49999999999999994; rounding to two decimals shows 0.5.

Next: Java Math Methods by Group

Full list with short descriptions: Java Math Methods index.

Frequently Asked Questions

java.lang.Math is a final class with only static methods and two constants, Math.PI and Math.E, for rounding, powers, roots, logarithms, trigonometry, random numbers, and overflow-safe integer math.
No. Every class in java.lang is imported automatically, so Math.sqrt(2.0) works in any Java file.
StrictMath gives bit-for-bit identical results on every computer. Math may use faster processor-specific code for functions like sin or exp, so their last digit can differ between platforms.
Math.round sends an exact .5 tie toward positive infinity and returns a long. Math.rint sends a tie to the even neighbour and returns a double.
Math.PI is only the double closest to pi, so the sine is about 1.2246467991473532E-16 instead of 0. Round the result or compare it with a small tolerance.

Browse every Math method

Open the methods index for categorized guides with examples and FAQs.

Math Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful