The java.lang.Math
class is a part of the java.lang
package, which is automatically imported in all Java programs. This means that you do not need to import the Math
class explicitly in your code.
You can use the Math
class to perform various mathematical operations and functions, such as trigonometric functions, logarithms, and random number generation. Here is an example of using the Math.sin
method to calculate the sine of an angle:
double x = Math.toRadians(30); // convert degrees to radians double y = Math.sin(x); System.out.println(y); // prints 0.5
Here is an example of using the Math.random
method to generate a random number between 0 and 1:
double x = Math.random(); System.out.println(x); // prints a random number between 0 and 1
You can also use the Math
class to perform basic arithmetic operations, such as addition, subtraction, multiplication, and division. Here is an example of using the Math.max
method to find the maximum of two numbers:
int x = 5; int y = 3; int z = Math.max(x, y); System.out.println(z); // prints 5