Java Math
The Math class provides static methods for common mathematical operations like Math.max(), Math.min(), Math.pow(), Math.sqrt(), and Math.random(), without needing to create an object.
These methods save you from writing your own math logic and are optimized and well-tested.
Math.max(a, b);
Math.pow(a, b);
Math.random();Common Math methods
Math.max(a,b) and Math.min(a,b) find the larger/smaller value. Math.pow(base, exp) raises a number to a power. Math.sqrt(x) finds a square root.
Random numbers
Math.random() returns a double between 0.0 (inclusive) and 1.0 (exclusive), often scaled to generate random integers in a range.
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10));
System.out.println(Math.pow(2, 3));
System.out.println(Math.sqrt(16));
}
}10
8.0
4.0Math.max returns the larger value, Math.pow computes 2^3, and Math.sqrt computes the square root of 16.
Key points
- Math methods are static, called without an object.
- Math.random() returns a double between 0.0 and 1.0.
- Math.pow and Math.sqrt handle powers and roots.
- Math.abs() returns the absolute value.
