The class “java.lang.Math” contains constants and methods that can be used to perform common mathematical functions. All of the constants and methods in the Math class are static. Common useful Math class methods include those used for finding an absolute value, finding maximum or minimum value, rounding values etc… To use a prewritten class other than “java.lang” you must use the path with the class name and import the class or import the package that contain the class.
Ex:
import javax.swing.*;
import java.util.*;
Easiest way to import prewritten classes is, importing whole package it contains. We use “*” to indicate we need all classes in the package as in above example.
Math class Methods:
· Min(x,y) Smaller of x and y
· Pow(x,y) X raised to the y power
· Sqrt(x) Square root of x
· Round(x) Closest integer to x(where x is a float or double, and the return value is an integer or long
· Rint(x) Closest integer to x(x is a double, and the return value is expressed as a double
· Floor(x) Largest integral value not greater than x
· Celi(x) Smallest integral value not greater than x
· Random() Random double number between 0.0 and 1.0
· Abs(x) Absolute value of x
· Sin(x) Sine of x
· Cos(x) Cosine of x
· Tan(x) Tangent of x
· Asin(x) Arcsine of x
· Acos(x) Arccosine of x
· Atan(x) Arctangent of x
· Atan2(x,y) That a component of the polar coordinate
· Exp(x) Exponent, where x is the base of the natural algorithms
· Log(x) Natural algorithm of x
Case: We will use fundamental class “Math” in “java.lang” to manipulate some numbers. We have used float numbers and while assigning values, the values follow letter”f” to indicate that casting shouldn’t carry out.
public class TestMathClass
{
public static void main(String[] args)
{
float num1 = 4f;
// becouse we're using float data type, it's better to use assigning its values followed by 'f'
float num2 = 5f;
float num3 = 6.3f;
float num4 = 6.8f;
System.out.println("Larger value amoung num1 and num2 is: " + Math.max(num1, num2));
System.out.println("Smaller value amoung num1 and num2 is: " + Math.min(num1, num2));
System.out.println("Power of num1 raised to the num2 power is: " + Math.pow(num1, num2));
System.out.println("Largest integral value not less than num3 is: " + Math.floor(num3));
System.out.println("Closest integer to num2 is: " + Math.rint(num4));
}
}
This is the output: