Chapter 15 of 77

Math Class in Java

In the previous chapter, we learned the arithmetic operators +, -, *, / and %. They are enough for simple calculations, but what if we need a square root, a power such as 210, or want to round 4.6 to 5? Java has no operator for these.

Instead, Java gives us a ready-made class called Math. It contains many useful mathematical constants and methods that we can use directly:

System.out.println(Math.sqrt(144));   // 12.0
System.out.println(Math.pow(2, 10));  // 1024.0
System.out.println(Math.round(4.6));  // 5

In this chapter, we will learn the most useful methods of the Math class, what each one returns, and the small traps that often show up in exams and interviews.

What is the Math Class?

Math is a class in the java.lang package. Classes in java.lang (like String and System) are available automatically, so we don't need any import.

A method is a named piece of code that does a task. You have already been using one: println(). We will learn to write our own methods in a later chapter. For now, you only need to know how to call a Math method:

Math . sqrt ( 144 )
 │      │      │
 │      │      └── the value we give it (called an argument)
 │      └───────── the method name
 └──────────────── the class name

The method then gives back (returns) a result, which we can print or store in a variable:

double root = Math.sqrt(144);

Notice that we write Math.sqrt() directly with the class name. We never create a Math object. In fact, we are not allowed to:

Math m = new Math();   // Error
error: Math() has private access in Math

All the methods of Math are static, which is why they are used with the class name. You will understand exactly what static means in the Static Keyword chapter.

Math Constants

The two most commonly used constants of the Math class are Math.PI and Math.E:

System.out.println(Math.PI);
System.out.println(Math.E);

Output:

3.141592653589793
2.718281828459045

Math.PI is π (the ratio of a circle's circumference to its diameter) and Math.E is e (the base of natural logarithms). Use Math.PI instead of typing 3.14; it is much more accurate. (Java 19 also added Math.TAU, which is 2π.)

abs(), max() and min()

Math.abs(x) returns the absolute value, that is, the number without its minus sign. Math.max(a, b) returns the bigger of two values and Math.min(a, b) returns the smaller one.

System.out.println(Math.abs(-7));
System.out.println(Math.abs(-7.5));
System.out.println(Math.max(10, 25));
System.out.println(Math.min(10, 25));
System.out.println(Math.max(10, 2.5));

Output:

7
7.5
25
10
10.0

These methods return the same type as their arguments. Math.abs(-7) gives an int, while Math.abs(-7.5) gives a double. In the last line, one argument is an int and the other is a double, so the int is converted to double (just like in the Type Conversion chapter) and the answer is 10.0.

Note that max() and min() take exactly two values. To find the largest of three numbers, nest them: Math.max(a, Math.max(b, c)).

pow(), sqrt() and cbrt()

  • Math.pow(a, b) returns ab (a raised to the power b).

  • Math.sqrt(x) returns the square root of x.

  • Math.cbrt(x) returns the cube root of x.

System.out.println(Math.pow(2, 10));
System.out.println(Math.pow(10, -2));
System.out.println(Math.sqrt(144));
System.out.println(Math.sqrt(2));
System.out.println(Math.cbrt(27));
System.out.println(Math.sqrt(-4));

Output:

1024.0
0.01
12.0
1.4142135623730951
3.0
NaN

Three things to notice:

  • All three methods always return a double. That is why we get 1024.0 and 12.0, not 1024 and 12. To store the result in an int, cast it: int result = (int) Math.pow(2, 10);

  • Java has no power operator. 2 ^ 10 is not 210 in Java; ^ is the bitwise XOR operator we saw in the Operators chapter, and 2 ^ 10 gives 8.

  • The square root of a negative number is not a real number, so Math.sqrt(-4) returns NaN ("Not a Number") instead of crashing.

Rounding: ceil(), floor(), round() and rint()

Rounding is the most commonly tested part of the Math class, so let's go slowly.

  • Math.ceil(x) (ceiling) rounds up to the nearest whole number.

  • Math.floor(x) rounds down to the nearest whole number.

  • Math.round(x) rounds to the nearest whole number. A value exactly halfway (like 4.5) goes up.

  • Math.rint(x) also rounds to the nearest whole number, but a halfway value goes to the nearest even number.

System.out.println(Math.ceil(4.1));
System.out.println(Math.floor(4.9));
System.out.println(Math.ceil(-4.1));
System.out.println(Math.floor(-4.1));
System.out.println(Math.round(4.5));
System.out.println(Math.round(4.4));
System.out.println(Math.round(-4.5));
System.out.println(Math.round(-4.6));
System.out.println(Math.rint(2.5));
System.out.println(Math.rint(3.5));

Output:

5.0
4.0
-4.0
-5.0
5
4
-4
-5
2.0
4.0

The negative numbers confuse many students, so think of a number line:

   -5        -4.6  -4.5  -4.1  -4
    |---------|-----|-----|-----|
    ← smaller                  larger →

ceil(-4.1)  = -4   (move right, "up", to the next whole number)
floor(-4.1) = -5   (move left, "down", to the next whole number)
round(-4.5) = -4   (halfway: Java rounds toward the larger value)
round(-4.6) = -5   (-4.6 is closer to -5)

A simple way to remember round(): for normal values it behaves like Math.floor(x + 0.5). So round(-4.5) is floor(-4.0) = -4, while round(4.5) is floor(5.0) = 5.

Also pay attention to the return types:

Method

Returns

Example

Math.ceil(double)

double

Math.ceil(4.1) → 5.0

Math.floor(double)

double

Math.floor(4.9) → 4.0

Math.rint(double)

double

Math.rint(2.5) → 2.0

Math.round(double)

long

Math.round(4.5) → 5

Math.round(float)

int

Math.round(2.5f) → 3

Because Math.round(double) returns a long, this line does not compile:

int marks = Math.round(87.6);   // Error: long cannot go into int without a cast

Write int marks = (int) Math.round(87.6); or store it in a long.

Rounding to Decimal Places

Math has no method like "round to 2 decimal places", but there is a common trick: multiply, round, then divide.

3.14159  × 100  →  314.159
round(314.159)  →  314
314 ÷ 100.0     →  3.14
System.out.println(Math.round(3.14159 * 100) / 100.0);
System.out.println(Math.round(3.14159 * 100) / 100);

Output:

3.14
3

The second line is a classic mistake. Math.round() returned the long 314, and 314 / 100 is integer division, which gives 3. Always divide by 100.0, not 100.

When you only want to display a value with 2 decimals, System.out.printf("%.2f", value) from the Output chapter is often simpler.

Math.random()

Math.random() returns a random double that is greater than or equal to 0.0 and less than 1.0. In maths notation the range is [0.0, 1.0): 0.0 is possible, 1.0 never is.

To get a random whole number between min and max (both included), use this formula:

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

Let's see why it works for a dice roll, where min = 1 and max = 6:

Math.random()              →  0.0  to  0.999...
× 6   (max - min + 1 = 6)  →  0.0  to  5.999...
(int) cast removes decimal →  0, 1, 2, 3, 4 or 5
+ 1   (min)                →  1, 2, 3, 4, 5 or 6
class Main {
    public static void main(String[] args) {

        double r = Math.random();
        int dice = (int) (Math.random() * 6) + 1;
        int otp = (int) (Math.random() * 9000) + 1000;

        System.out.println("Random double: " + r);
        System.out.println("Dice: " + dice);
        System.out.println("4-digit OTP: " + otp);
    }
}

One possible output (yours will be different every time you run it):

Random double: 0.7302458211196487
Dice: 4
4-digit OTP: 5821

For the OTP, max - min + 1 is 9999 - 1000 + 1 = 9000, so the result is between 1000 and 9999.

Be careful with brackets. (int) Math.random() * 6 is always 0, because the cast happens first: (int) 0.73 is 0, and 0 * 6 is 0. The multiplication must be inside the brackets before casting.

(Math.random() is fine for games and practice. For passwords, real OTPs, or anything security-related, Java provides java.security.SecureRandom instead.)

Other Useful Methods

Method

What it does

Example → result

Math.hypot(x, y)

√(x² + y²), the hypotenuse

Math.hypot(3, 4) → 5.0

Math.log(x)

Natural logarithm (base e)

Math.log(Math.E) → 1.0

Math.log10(x)

Logarithm base 10

Math.log10(1000) → 3.0

Math.exp(x)

ex

Math.exp(1) → 2.718281828459045

Math.signum(x)

-1.0, 0.0 or 1.0 depending on the sign

Math.signum(-9.5) → -1.0

Math.toRadians(deg)

Converts degrees to radians

Math.toRadians(180) → π

Math.sin(x), cos(x), tan(x)

Trigonometry; x must be in radians

Math.cos(Math.toRadians(60)) → about 0.5

Math.floorDiv(a, b)

Division that always rounds down

Math.floorDiv(-7, 2) → -4

Math.floorMod(a, b)

Remainder with the sign of b

Math.floorMod(-7, 3) → 2

Math.addExact(a, b)

Adds, but reports overflow instead of giving a wrong answer

See below

Math.clamp(v, min, max)

Keeps v inside the range min to max (Java 21+)

Math.clamp(150, 0, 100) → 100

Trigonometry results are often not perfectly exact, because double cannot store most decimal values exactly. For example, Math.sin(Math.toRadians(30)) prints 0.49999999999999994, not 0.5. This is normal floating-point behaviour, not a bug.

floorMod(): The Negative Remainder Trap

In the Operators chapter we learned that % gives the remainder. With negative numbers, the result of % takes the sign of the left number:

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

Output:

-3
-1
-1
-4
1
2

The / operator rounds toward zero (-3.5 becomes -3), while floorDiv() rounds down (-3.5 becomes -4). Matching that, floorMod() always gives a result between 0 and b - 1 when b is positive. This is very handy for "wrap-around" problems, such as finding which day of the week it was some days ago, or rotating an index in a circular array.

Overflow and addExact()

From the Data Types chapter, we know an int can hold at most 2147483647. Java also gives this value a ready-made name, Integer.MAX_VALUE, which we use below. Going past it silently wraps around to a negative number. Math.addExact() (and its friends subtractExact(), multiplyExact()) refuse to give a wrong answer:

class Main {
    public static void main(String[] args) {
        int big = Integer.MAX_VALUE;
        System.out.println(big + 1);
        System.out.println(Math.addExact(big, 1));
    }
}

Output:

-2147483648
Exception in thread "main" java.lang.ArithmeticException: integer overflow
	at java.base/java.lang.Math.addExact(Math.java:883)
	at Main.main(Main.java:5)

The normal + quietly gave a wrong negative result. addExact() stopped the program with an ArithmeticException instead (the line number inside Math.java may differ on your Java version). We will learn how to handle exceptions in the Exception Handling chapter. A loud error is usually much better than a silently wrong bank balance.

A related trap: Math.abs(Integer.MIN_VALUE) returns -2147483648, a negative number! The positive value 2147483648 does not fit in an int, so it overflows back to itself. (Math.absExact(), added in Java 15, throws an exception in this case instead.)

Worked Examples

Let's use the Math class to solve some typical problems:

class Main {
    public static void main(String[] args) {

        // 1. Area and circumference of a circle
        double radius = 7;
        double area = Math.PI * Math.pow(radius, 2);
        double circumference = 2 * Math.PI * radius;
        System.out.println("Area: " + area);
        System.out.println("Area (2 decimals): " + Math.round(area * 100) / 100.0);
        System.out.println("Circumference (2 decimals): " + Math.round(circumference * 100) / 100.0);

        // 2. Compound interest: A = P * (1 + r/100)^t
        double principal = 10000;
        double rate = 8;
        int years = 3;
        double amount = principal * Math.pow(1 + rate / 100, years);
        System.out.println("Amount: " + Math.round(amount * 100) / 100.0);

        // 3. Distance between (1, 2) and (4, 6)
        double distance = Math.sqrt(Math.pow(4 - 1, 2) + Math.pow(6 - 2, 2));
        System.out.println("Distance: " + distance);
        System.out.println("Using hypot: " + Math.hypot(4 - 1, 6 - 2));

        // 4. Roots of x^2 - 5x + 6 = 0
        double a = 1, b = -5, c = 6;
        double d = Math.sqrt(b * b - 4 * a * c);
        System.out.println("Root 1: " + (-b + d) / (2 * a));
        System.out.println("Root 2: " + (-b - d) / (2 * a));

        // 5. Pages needed for 53 students, 10 per page
        int students = 53;
        int perPage = 10;
        int pages = (int) Math.ceil((double) students / perPage);
        System.out.println("Pages: " + pages);
    }
}

Output:

Area: 153.93804002589985
Area (2 decimals): 153.94
Circumference (2 decimals): 43.98
Amount: 12597.12
Distance: 5.0
Using hypot: 5.0
Root 1: 3.0
Root 2: 2.0
Pages: 6

Let's check a few of these by hand:

  • Compound interest: A = 10000 × (1.08)3 = 10000 × 1.259712 = 12597.12.

  • Distance: √((4 − 1)² + (6 − 2)²) = √(9 + 16) = √25 = 5.

  • Quadratic: the discriminant is (−5)² − 4 × 1 × 6 = 25 − 24 = 1, so √1 = 1. The roots are (5 + 1) / 2 = 3 and (5 − 1) / 2 = 2.

  • Pages: 53 / 10 = 5.3 pages, and we can't print 0.3 of a page, so we round up to 6. Notice the (double) cast: without it, 53 / 10 would be integer division (5), and Math.ceil(5) would give 5.0, which is wrong.

(This quadratic example only works when the discriminant is not negative. Once we learn if statements in the next chapter, we can check that first.)

Common Mistakes

  • Using ^ for power. 2 ^ 3 is XOR and gives 1. Use Math.pow(2, 3).

  • Forgetting that pow(), sqrt(), ceil() and floor() return double. int x = Math.sqrt(16); does not compile. Cast it: (int) Math.sqrt(16).

  • Forgetting that round(double) returns long. int x = Math.round(2.7); does not compile.

  • Integer division before ceil(). Math.ceil(7 / 2) gives 3.0, not 4.0, because 7 / 2 is already 3. Use Math.ceil(7 / 2.0).

  • Wrong brackets with random(). (int) Math.random() * 6 is always 0.

  • Passing degrees to sin() or cos(). They expect radians. Use Math.toRadians() first.

  • Trusting pow() for huge whole numbers. A double has only about 15 to 16 significant digits. (long) Math.pow(3, 39) gives 4052555153018976256, but the exact value of 339 is 4052555153018976267. For exact large integer powers, multiply with long values or use BigInteger.

Interview Corner

  • What is Math.round(-2.5)? -2. Halfway values round toward positive infinity, so -2.5 goes to -2 and 2.5 goes to 3.

  • Can we create an object of Math? No. Its constructor is private, and the class is final, so it cannot be extended either. All its members are static and used through the class name.

  • Do we need to import Math? No, it is in java.lang, which is imported automatically.

  • What is the range of Math.random()? 0.0 (inclusive) to 1.0 (exclusive).

  • What is the difference between Math and StrictMath? StrictMath guarantees bit-for-bit identical results on every platform. Math is allowed to use faster, platform-specific implementations for some methods, as long as the result stays within a tiny allowed error. For everyday code, use Math.

  • What does Math.sqrt(-1) return? NaN. It does not throw an exception.

Quick Revision

Need

Use

Returns

Absolute value, bigger, smaller

abs(), max(), min()

Same type as the arguments

Power, square root, cube root

pow(), sqrt(), cbrt()

double

Round up, round down

ceil(), floor()

double

Round to nearest

round()

long (or int for a float)

Random number

random()

double in [0.0, 1.0)

Remainder that is never negative (for positive divisor)

floorMod()

Same type as the arguments

The Math class turns long formulas into a single readable line. Just keep an eye on the return types and on integer division, and you will avoid almost every Math-related bug.