JavaMath
The Java Math class has many methods that allows you to perform mathematical tasks on numbers.
Math.max(x,y)
TheMath.max(x,y) method can be used to find the highest value ofx andy:
Math.min(x,y)
TheMath.min(x,y) method can be used to find the lowest value ofx andy:
Math.sqrt(x)
TheMath.sqrt(x) method returns the square root ofx:
Math.abs(x)
TheMath.abs(x) method returns the absolute (positive) value ofx:
Math.pow(x, y)
TheMath.pow(x, y) method returns the value ofx raised to the power ofy:
Note:Math.pow(2, 8) means2 multiplied by itself 8 times:
2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 256
Note: TheMath.pow() method always returns adouble, even if the result is a whole number. For example,Math.pow(2, 8) returns256.0 (not256).
Rounding Methods
Java has several methods for rounding numbers:
Math.round(x)- rounds to the nearest integerMath.ceil(x)- rounds up (returns the smallest integer greater than or equal to x)Math.floor(x)- rounds down (returns the largest integer less than or equal to x)
Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
To get more control over the random number, for example, if you only want a random number between 0 and 100, you can use the following formula:
Note:Math.random() returns adouble. To get an integer, you need tocast it with(int).
Complete Math Reference
For a complete reference of Math methods, go to ourJava Math Methods Reference.

