Math Class in Java
Introduction
The `Math` class in Java is a utility class that provides various static methods for performing mathematical operations. It is part of the `java.lang` package and does not require import statements.
Basic Mathematical Operations
The `Math` class provides methods for basic arithmetic operations like addition, subtraction, multiplication, and division.
int sum = Math.addExact(5, 3); // Output: 8
int difference = Math.subtractExact(10, 5); // Output: 5
int product = Math.multiplyExact(2, 3); // Output: 6
double quotient = Math.floorDiv(10, 3); // Output: 3.0Rounding and Truncation
The `Math` class offers methods for rounding and truncating floating-point numbers.
double roundedValue = Math.round(7.25); // Output: 7
double floorValue = Math.floor(3.9); // Output: 3.0
double ceilValue = Math.ceil(2.1); // Output: 3.0Exponents and Logarithms
The `Math` class provides methods for calculating exponents and logarithms.
double power = Math.pow(2, 3); // Output: 8.0
double exponential = Math.exp(1.0); // Output: 2.718281828459045
double logarithm = Math.log(10); // Output: 2.302585092994046Trigonometric Functions
The `Math` class includes trigonometric functions like sine, cosine, and tangent.
double sineValue = Math.sin(Math.toRadians(30)); // Output: 0.5
double cosineValue = Math.cos(Math.toRadians(45)); // Output: 0.7071067811865476
double tangentValue = Math.tan(Math.toRadians(60));// Output: 1.7320508075688774Get Ravindu Madhubhashana’s stories in your inbox
Join Medium for free to get updates from this writer.
Random Numbers
The `Math` class enables the generation of random numbers between 0.0 and 1.0.
double randomValue = Math.random(); // Output: A random number between 0.0 and 1.0Minimum and Maximum
The `Math` class offers methods to find the minimum and maximum values in a set of numbers.
int minValue = Math.min(4, 7); // Output: 4
int maxValue = Math.max(9, 2); // Output: 9Absolute Value
The `Math` class allows you to get the absolute value of a number.
int absoluteValue = Math.abs(-5); // Output: 5Other Useful Methods
The `Math` class includes other useful methods such as the square root, the cube root, and the signum.
double squareRoot = Math.sqrt(25); // Output: 5.0
double cubeRoot = Math.cbrt(8); // Output: 2.0
double sign = Math.signum(-10); // Output: -1.0Conclusion
- The `Math` class in Java provides a wide range of mathematical operations essential for many applications.
- By effectively utilizing the `Math` class, developers can easily perform complex mathematical calculations.
This expanded guide provides a more detailed explanation of each topic along with relevant code examples to demonstrate the usage of the `Math` class in Java.









