Java Math Class
The java.lang.Math class is a utility class (i.e. contains static methods only) in Java that contains certain methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. The fields of this class are also static.
Its signature is as follows −
public final class Math extends Object
Fields
Following are the static fields of java.lang.Math class −
static double E − This is the double value that is closer than any other to E, the base of the natural logarithms.
static double PI − This is the double value that is closer than any other to PI, the ratio of the circumference of a circle to its diameter.
Class Methods
Below is a list describing several methods that Java Math class offers:
Table 1. Methods in java.lang.Math
Method | Argument Type(s) | Functionality |
---|---|---|
|
| Absolute value |
|
| Arc cosine |
|
| Arc sine |
|
| Arc tangent |
|
| Angle part of rectangular-to-polar coordinate transform |
|
| Smallest whole number greater than orequal to |
|
| Cosine |
|
|
|
|
| Largest whole number less than or equal to |
|
| Natural logarithm of |
|
| Maximum |
|
| Minimum |
|
|
|
|
| Random-number generator |
|
| Converts double value to integral value in double format |
|
| Rounds to whole number |
|
| Sine |
|
| Square root |
|
| Tangent |
Math Class Example
See the following example to demonstrate some important methods of Math class.
MathClassDemo.java
public class MathClassDemo {
public static void main(String[] args) {
double theta = 90;
System.out.println(Math.PI); //3.141592653589793
System.out.println(Math.E); //2.718281828459045
System.out.println(Math.abs(-99)); //99
double r = Math.cos(Math.PI * theta);
System.out.println("r = " + r); //r = 1.0
System.out.println(Math.ceil(1.1)); //2.0
System.out.println(Math.ceil(-1.1)); //-1.0
System.out.println(Math.floor(1.1)); //1.0
System.out.println(Math.floor(-1.1));//-2.0
System.out.println(Math.round(1.1)); //1
System.out.println(Math.round(1.5)); //2
System.out.println(Math.max(1.1, -2.3)); //1.1
System.out.println(Math.min(2.5, -0.5)); //-0.5
System.out.println(Math.log(1)); //0.0
System.out.println(Math.log10(100)); //2.0
System.out.println(Math.exp(0)); //1.0
System.out.println(Math.sqrt(9)); //3.0
System.out.println(Math.cbrt(64)); //4.0
System.out.println(Math.random()); //0.663122570081919
System.out.println(Math.toDegrees(Math.asin(0.5))); //30.000000000000004
System.out.println(Math.pow(2,3)); //8.0
}
}
Output:
3.141592653589793
2.718281828459045
99
r = 1.0
2.0
-1.0
1.0
-2.0
1
2
1.1
-0.5
0.0
2.0
1.0
3.0
4.0
0.663122570081919
30.000000000000004
8.0