The Math class in Java is a class in the java.lang package that contains a set of methods for performing basic mathematical operations such as calculating the absolute value, the largest and smallest of two numbers, the square root, and so on. The methods in the Math class are all static, which means that they can be called without creating an instance of the Math class.
Here are some of the commonly used methods of the Math class:
abs(x)
: Returns the absolute value of the argument x.max(x, y)
: Returns the greater of the two arguments x and y.min(x, y)
: Returns the lesser of the two arguments x and y.pow(x, y)
: Returns the value of x raised to the power of y.sqrt(x)
: Returns the square root of the argument x.ceil(x)
: Returns the smallest integer that is greater than or equal to the argument x.floor(x)
: Returns the largest integer that is less than or equal to the argument x.
Here is an example of how to use the Math class to perform some basic mathematical operations:
int x = 10;
int y = 20;
double result1 = Math.abs(x); // result1 will be 10
double result2 = Math.max(x, y); // result2 will be 20
double result3 = Math.min(x, y); // result3 will be 10
double result4 = Math.pow(x, y); // result4 will be 100000000000000000000
double result5 = Math.sqrt(x); // result5 will be 3.1622776601683795
double result6 = Math.ceil(x); // result6 will be 10
double result7 = Math.floor(x); // result7 will be 10
It is worth noting that the Math class also has some constants such as PI
and E
that can be used in your calculations. For example, you can use Math.PI
to get the value of pi and Math.E
to get the value of the base of the natural logarithm.