Java Math Class

The Math class (in java.lang, no import needed) has static methods for common maths. You call them like Math.sqrt(16).

Common methods

public class Main {
    public static void main(String[] args) {
        System.out.println(Math.max(10, 25));
        System.out.println(Math.min(10, 25));
        System.out.println(Math.abs(-7.5));
        System.out.println(Math.pow(2, 10));      // 2 to the power 10
        System.out.println(Math.sqrt(81));
        System.out.println(Math.cbrt(27));        // cube root
        System.out.println(Math.PI);
    }
}
Output

25
10
7.5
1024.0
9.0
3.0
3.141592653589793

Rounding

public class Round {
    public static void main(String[] args) {
        double x = 4.5;
        System.out.println(Math.round(x));    // 5   nearest whole number
        System.out.println(Math.round(4.4));  // 4
        System.out.println(Math.ceil(4.1));   // 5.0 always up
        System.out.println(Math.floor(4.9));  // 4.0 always down
        System.out.println(Math.round(-4.5)); // -4  (rounds half up)
        System.out.println(Math.rint(4.5));   // 4.0 (half to even)
    }
}
Output

5
4
5.0
4.0
-4
4.0

MethodWhat it does
round(x)Nearest whole number (as long or int)
ceil(x)Up to the next whole number (double)
floor(x)Down to the whole number (double)

Random numbers

Math.random() gives a double from 0.0 up to (but not including) 1.0. To get a number in a range, use a formula or the Random class.

import java.util.Random;

public class Rand {
    public static void main(String[] args) {
        double r = Math.random();
        System.out.println(r >= 0.0 && r < 1.0);

        int dice = (int) (Math.random() * 6) + 1;        // 1 to 6
        System.out.println(dice >= 1 && dice <= 6);

        Random rnd = new Random(42);                      // a fixed seed gives the same numbers
        System.out.println(rnd.nextInt(100));
        System.out.println(rnd.nextInt(100));
        System.out.println(new Random().nextInt(1, 7) <= 6);   // 1 to 6, easy way
    }
}
Output

true
true
30
63
true

With a fixed seed (42) the Random class always gives the same numbers, which is good for tests. Without a seed the numbers are different on every run.

Exact math

Normal int math can overflow without any error. The Math.xxxExact() methods throw an exception instead:

public class Exact {
    public static void main(String[] args) {
        int big = Integer.MAX_VALUE;
        System.out.println(big + 1);                 // wrong value, no error
        try {
            System.out.println(Math.addExact(big, 1));
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
Output

-2147483648
Caught: integer overflow

Division by zero

public class Zero {
    public static void main(String[] args) {
        System.out.println(5.0 / 0);        // Infinity: no error for decimals
        System.out.println(0.0 / 0);        // NaN: not a number
        System.out.println(5 / 0);          // int: exception
    }
}
Output

Infinity
NaN
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Zero.main(Zero.java:5)

Note: For money use BigDecimal and not double. Next: Java if else.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.