Math Class in Java
In Java, the java.lang.Math class provides a set of methods for performing basic numeric
operations such as elementary exponential, logarithmic, square root, and trigonometric
functions. The methods in the Math class are static, so you can call them directly on the class
without creating an instance of it. Here are some commonly used methods in the Math class:
1.Basic arithmetic operations:
● addExact(int x, int y): Adds two integers, checking for overflow.
● subtractExact(int x, int y): Subtracts one integer from another, checking for overflow.
● multiplyExact(int x, int y): Multiplies two integers, checking for overflow.
● incrementExact(int a): Increments an integer, checking for overflow.
● decrementExact(int a): Decrements an integer, checking for overflow.
2. Exponential and logarithmic functions:
● exp(double a): Returns the base of the natural logarithm (e) raised to the power of a.
● log(double a): Returns the natural logarithm (base e) of a.
● pow(double a, double b): Returns a raised to the power of b.
3.Trigonometric functions:
● sin(double a), cos(double a), tan(double a): Sine, cosine, and tangent of an angle (in
radians).
● asin(double a), acos(double a), atan(double a): Arcsine, arccosine, and arctangent
functions.
4.Square root and rounding:
● sqrt(double a): Returns the square root of a.
● ceil(double a): Returns the smallest integer that is greater than or equal to a.
● floor(double a): Returns the largest integer that is less than or equal to a.
● round(float a), round(double a): Returns the closest long or int to the argument, rounding
to the nearest integer.
5.Random number generation:
● random(): Returns a pseudo-random double value between 0.0 and 1.0.
Keep in mind that Math.random() generates a pseudo-random number between 0.0
(inclusive) and 1.0 (exclusive).
Example:
Here's an example demonstrating the use of some Math class methods:
public class MathExample {
public static void main(String[] args) {
double x = 4.0;
double y = 2.0;
// Basic arithmetic operations
System.out.println("Addition: " + Math.addExact(5, 3));
System.out.println("Subtraction: " + Math.subtractExact(5, 3));
System.out.println("Multiplication: " + Math.multiplyExact(5, 3));
// Exponential and logarithmic functions
System.out.println("Power: " + Math.pow(x, y));
System.out.println("Natural Logarithm: " + Math.log(x));
// Trigonometric functions
System.out.println("Sine: " + Math.sin(Math.PI / 2));
System.out.println("Cosine: " + Math.cos(Math.PI));
System.out.println("Tangent: " + Math.tan(Math.PI / 4));
// Square root and rounding
System.out.println("Square Root: " + Math.sqrt(x));
System.out.println("Ceil: " + Math.ceil(4.3));
System.out.println("Floor: " + Math.floor(4.9));
System.out.println("Round: " + Math.round(4.6));
// Random number generation
System.out.println("Random: " + Math.random());
}
}