Menu

Java Math Class: pow, sqrt, abs, round, random, and More

How to use Java's Math class: Math.pow, Math.sqrt, Math.abs, Math.max and Math.min, rounding with round, floor and ceil, generating random numbers in a range with Math.random, and the constants PI and E, with the return type of each.

This page includes runnable editors - edit, run, and see output instantly.

A Toolbox of Static Methods

java.lang.Math is a class full of ready-made math functions: powers, roots, absolute values, rounding, trigonometry, logarithms and random numbers. Two things make it easy to use:

  • It lives in java.lang, which every Java file imports automatically. There is no import line to write.
  • Every method is static. You call it on the class name, Math.sqrt(25), and never create a Math object. The static members page explains what static means.

Notice that some results print with .0 and some do not. Each Math method has a fixed return type, and knowing it is most of what there is to learn about this class.

MethodDoesReturns
Math.pow(a, b)a to the power bdouble
Math.sqrt(x)square rootdouble
Math.cbrt(x)cube rootdouble
Math.abs(x)absolute valuesame type as x
Math.max(a, b) / Math.min(a, b)larger / smaller of twothe wider of the two types
Math.round(x)nearest whole numberlong for a double, int for a float
Math.floor(x) / Math.ceil(x)round down / round updouble
Math.random()random number from 0.0 up to 1.0double
Math.PI, Math.Ethe constants π and edouble

Math.pow: Powers

Math.pow(base, exponent) raises a number to a power. It takes two double parameters and returns a double, even when you pass whole numbers:

To store the result in an int, cast it with (int). For small whole-number powers the double result is exact, so the cast gives the right answer. Large results are where the cast goes wrong: a double above Integer.MAX_VALUE (2,147,483,647) casts to exactly Integer.MAX_VALUE, so (int) Math.pow(2, 40) gives 2147483647. Cast to long for bigger powers, and remember that above 2⁵³ a double cannot represent every whole number exactly. The type casting page covers what a cast does to the value.

Java has no power operator. 2 ^ 3 compiles, but ^ is bitwise XOR, and the result is 1, not 8. That is one of the most common beginner bugs in Java math code.

A double of ten million or more prints in scientific notation, which surprises people the first time they print a power of ten:

1.0E7 means 1.0 × 10⁷. The value is the same; only the printed form changes. Cast to long, or format with String.format("%.0f", value), to print it as plain digits.

Math.sqrt and Math.cbrt: Roots

Math.sqrt(x) returns the square root of x as a double. Math.cbrt(x) returns the cube root.

The square root of a negative number is not a real number, so Math.sqrt(-4) returns NaN ("not a number") instead of throwing an exception. NaN spreads through any arithmetic it touches, so check inputs before taking a root if negative values are possible. Math.hypot(a, b) computes sqrt(a*a + b*b) directly, which is a common way to get the distance between two points.

Math.abs: Absolute Value

Math.abs(x) removes the sign. Unlike pow and sqrt, it returns the same type you give it: an int for an int, a double for a double.

The usual use is a difference where you care about size, not direction, as in the distance between two positions.

Math.max and Math.min

Math.max(a, b) returns the larger of two values and Math.min(a, b) the smaller. They take exactly two arguments. For three or more, nest the calls:

When the two arguments have different types, the narrower one is widened first. Math.max(3, 7.5) compares two double values and returns a double. The last example clamps a value into the range 0 to 100: Math.min caps it at 100, Math.max keeps it from going below 0.

Rounding: round, floor, ceil

Java has three rounding methods, and they differ both in direction and in return type:

  • Math.round goes to the nearest whole number. A value exactly halfway rounds up, towards positive infinity, so 2.5 becomes 3 and -2.5 becomes -2. It returns a long for a double argument (and an int for a float).
  • Math.floor always rounds down, towards negative infinity, and returns a double.
  • Math.ceil always rounds up, towards positive infinity, and returns a double.
  • A cast (int) is not rounding at all: it drops the fractional part, which moves positive numbers down and negative numbers up.

Because Math.round(double) returns a long, assigning it to an int does not compile without a cast:

int n = Math.round(2.6);          // error: incompatible types: possible lossy conversion from long to int
int m = (int) Math.round(2.6);    // OK, m is 3
long k = Math.round(2.6);         // OK

To round to a number of decimal places, scale up, round, and scale back down. Dividing by 100.0 (a double) rather than 100 keeps the decimals:

The second line divides a long by an int, which is integer division, so the decimals are lost. When you only need to display a rounded number, String.format("%.2f", value) is simpler and does not change the stored value.

Math.random: Random Numbers

Math.random() returns a double that is at least 0.0 and less than 1.0. The value is different on every call, so the output of the programs in this section changes each time you press Run.

To get a whole number in a range, stretch that value, cast it, and shift it. For a whole number from min to max, both included:

int value = (int) (Math.random() * (max - min + 1)) + min;

Here is how that works for a die, where min is 1 and max is 6:

  1. Math.random() * 6 gives a double from 0.0 up to, but not including, 6.0.
  2. (int) drops the fraction, giving one of 0, 1, 2, 3, 4, 5.
  3. + 1 shifts that to 1, 2, 3, 4, 5, 6.

The first line shows five random rolls. The second line checks ten thousand rolls and, in practice, always prints lowest: 1, highest: 6: the formula reaches both ends of the range and never goes past them.

The parentheses around Math.random() * (max - min + 1) matter. A cast applies to the value right after it, so (int) Math.random() * 6 casts Math.random() first. That is always 0, and 0 * 6 is 0, so every "roll" comes out the same.

Math.random() is fine for games and exercises. For anything more, the java.util.Random class and ThreadLocalRandom.current().nextInt(min, max + 1) (in java.util.concurrent) return integers directly, and Random can take a seed to repeat the same sequence in tests. None of these are suitable for passwords or security tokens; use java.security.SecureRandom for those.

Math.PI and Math.E

Math.PI (π) and Math.E (Euler's number e) are static final double constants:

Use them instead of typing 3.14. They are as precise as a double allows, and the name tells the reader what the number is.

Integer Results vs Double Results

Most Math methods take and return double. When you feed them int values, Java widens the arguments to double automatically, but the arithmetic you write before the call still happens in int. This is where most wrong answers come from:

items / perBox is 7 / 2, and dividing two int values discards the remainder, so it is 3 before Math.ceil ever sees it. Math.ceil(3.0) is 3.0. Make one operand a double, with a cast or a literal like 4.0, so the division keeps its fraction. The operators page explains integer division in more detail.

The general rule: decide which type you want at the end, make the division or multiplication happen in double when fractions matter, and cast back to int or long only once, at the end.

Other Useful Methods

A few more methods from the same class, all called the same way:

  • Math.log is the natural logarithm; Math.log10 is base 10.
  • Math.floorMod(a, b) gives a remainder with the sign of b, which is what you want for wrapping around a range such as days of the week. The % operator keeps the sign of a.
  • The trigonometry methods (sin, cos, tan) take radians. Convert degrees with Math.toRadians first.
  • Math.addExact, Math.multiplyExact and their siblings throw an ArithmeticException on overflow instead of silently wrapping around to a negative number.

Frequently Asked Questions

How do I use Math.pow in Java?

Math.pow(base, exponent) returns base raised to exponent as a double, so Math.pow(2, 3) is 8.0. To store the result in an int, cast it: int n = (int) Math.pow(2, 10); gives 1024. Java has no ^ power operator; ^ is bitwise XOR.

How do I generate a random number in a range with Math.random?

Math.random() returns a double from 0.0 up to but not including 1.0. For a whole number from min to max inclusive, use (int) (Math.random() * (max - min + 1)) + min. A die roll is (int) (Math.random() * 6) + 1.

Do I need to import the Math class in Java?

No. Math is in the java.lang package, which every Java file imports automatically. All its methods are static, so you call them on the class name, as in Math.sqrt(16), without creating an object.

Why does Math.round return a long in Java?

Math.round(double) returns a long because a double can hold values far larger than an int. Assigning the result to an int needs a cast: int n = (int) Math.round(2.6);. Math.round(float) returns an int.

What is the difference between Math.floor, Math.ceil and Math.round?

Math.floor rounds down (2.7 becomes 2.0, -2.3 becomes -3.0), Math.ceil rounds up (2.1 becomes 3.0), and Math.round goes to the nearest whole number, with halves going up (2.5 becomes 3). floor and ceil return a double; round returns a long.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED