The Math Class
The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
Unlike some of the other classes we've looked at, all methods in the Math class are static. You do not need to create an object of the Math class to use them; you invoke them directly using the class name (Math.methodName()).
Important Math Methods
Here is a quick rundown of the most commonly used methods in the Math class.
| Method | Description | Example |
|---|---|---|
Math.abs(x) | Returns the absolute (positive) value of x. | Math.abs(-10.5) ➔ 10.5 |
Math.max(x, y) | Returns the highest value of x and y. | Math.max(5, 10) ➔ 10 |
Math.min(x, y) | Returns the lowest value of x and y. | Math.min(5, 10) ➔ 5 |
Math.round(x) | Rounds x to the nearest integer. | Math.round(4.6) ➔ 5 |
Math.ceil(x) | Rounds x UP to the nearest integer. | Math.ceil(4.2) ➔ 5.0 |
Math.floor(x) | Rounds x DOWN to the nearest integer. | Math.floor(4.8) ➔ 4.0 |
Math.pow(x, y) | Returns the value of x raised to the power of y. | Math.pow(2, 3) ➔ 8.0 |
Math.sqrt(x) | Returns the square root of x. | Math.sqrt(25) ➔ 5.0 |
Generating Random Numbers
One of the most useful methods for beginners is Math.random().
The Math.random() method returns a random double value strictly between 0.0 (inclusive) and 1.0 (exclusive).
public class LabMath1 {
public static void main(String args[]) {
// Generates a random double between 0.0 and 0.999...
double randomDouble = Math.random();
System.out.println("Random Double: " + randomDouble);
// To generate a random integer between 0 and 100
int randomInt = (int) (Math.random() * 101);
System.out.println("Random Integer (0 to 100): " + randomInt);
}
}
[!TIP] If you need more advanced random generation (like generating random booleans or working with seeds), you should use the
java.util.Randomclass instead ofMath.random().