Java's Math class provides many useful methods to perform mathematical tasks. You don't need to create an object of the Math class to use its methods; they are all static.
Math.max() and Math.min()The Math.max(x, y) method can be used to find the highest value of x and y, and Math.min(x, y) can be used to find the lowest value.
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10)); // Outputs 10
System.out.println(Math.min(5, 10)); // Outputs 5
}
}
Math.sqrt() and Math.abs()Math.sqrt(x) returns the square root of x.Math.abs(x) returns the absolute (positive) value of x.
public class Main {
public static void main(String[] args) {
System.out.println(Math.sqrt(64)); // Outputs 8.0
System.out.println(Math.abs(-4.7)); // Outputs 4.7
}
}
Math.random()Math.random() returns a random double number between 0.0 (inclusive) and 1.0 (exclusive).
To get a random number within a specific range, you can use a formula. For example, to get a random integer between 0 and 100:
public class Main {
public static void main(String[] args) {
// A random number between 0.0 and 1.0
System.out.println(Math.random());
// A random integer between 0 and 100
int randomNumber = (int)(Math.random() * 101); // 0 to 100
System.out.println(randomNumber);
}
}
| Method | Description |
|---|---|
Math.round(x) |
Rounds a floating-point number to the nearest integer. |
Math.ceil(x) |
Rounds a number UP to the nearest integer. |
Math.floor(x) |
Rounds a number DOWN to the nearest integer. |
Math.pow(x, y) |
Returns the value of x to the power of y. |
Math.PI |
A constant representing the value of PI. |