The java.lang.Math
class in Java provides a set of methods for performing common mathematical operations. It includes methods for basic arithmetic, trigonometry, exponentiation, rounding, and more. Here’s an overview of the Math
class along with examples of its usage:
Constants
The Math
class defines several constants such as π (pi) and e (Euler’s number).
double pi = Math.PI;
double e = Math.E;
Basic Arithmetic Operations
The Math
class provides methods for common arithmetic operations like addition, subtraction, multiplication, and division.
double sum = Math.addExact(10, 20); // 30
double difference = Math.subtractExact(30, 10); // 20
double product = Math.multiplyExact(5, 4); // 20
double quotient = Math.floorDiv(10, 3); // 3
Exponentiation and Logarithm
The Math
class provides methods for exponentiation and logarithmic functions.
double power = Math.pow(2, 3); // 2^3 = 8
double squareRoot = Math.sqrt(16); // 4
double logarithm = Math.log(10); // Natural logarithm
double logarithmBase10 = Math.log10(100); // Base 10 logarithm
Trigonometric Functions
The Math
class provides methods for trigonometric functions like sine, cosine, and tangent.
double sine = Math.sin(Math.PI / 6); // sin(π/6) = 0.5
double cosine = Math.cos(Math.PI / 3); // cos(π/3) = 0.5
double tangent = Math.tan(Math.PI / 4); // tan(π/4) = 1
Rounding and Absolute Value
The Math
class provides methods for rounding numbers and obtaining the absolute value.
double roundedValue = Math.round(3.7); // 4
double floorValue = Math.floor(3.7); // 3
double ceilingValue = Math.ceil(3.2); // 4
double absoluteValue = Math.abs(-10); // 10
Random Number Generation
The Math
class includes methods for generating random numbers.
double randomValue = Math.random(); // Random value between 0.0 and 1.0
int randomInt = (int) (Math.random() * 100); // Random integer between 0 and 99