Thursday 26 January 2012

Fundamental classes in the java.lang package

Using the Math class


The Math class is final and all the methods defined in the Math class are static, which means you cannot inherit from the Math class and override these methods. Also, the Math class has a private constructor, so you cannot instantiate it.

The Math class has the following methods: ceil(), floor(), max(), min(), random(), abs(), round(), sin(), cos(), tan(), and sqrt().

The ceil() method returns the smallest double value that is not less than the argument and is equal to a mathematical integer. For instance:

Math.ceil(5.4)                       // gives 6
Math.ceil(-6.3)                     // gives -6


The floor() method returns the largest double value that is not greater than the argument and is equal to a mathematical integer. For instance:

Math.floor(5.4)                        // gives 5
Math.floor(-6.3)                      // gives -7


The max() method takes two numeric arguments and returns the greater of the two. It is overloaded for int, long, float, or double arguments. For instance:

x = Math.max(10,-10);          // returns 10


The min() method takes two numeric arguments and returns the smaller of the two. It is overloaded for int, long, float, or double arguments. For instance:

x = Math.min(10,-10);          // returns -10


The random() method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

The abs() method returns the absolute value of the argument. It is overloaded to take an int, long, float, or double argument. For instance:

Math.abs(-33)                       // returns 33


The round() method returns the integer closest to the argument (overloaded for float and double arguments). If the number after the decimal point is less than 0.5, Math.round() returns the same result as Math.floor(). In all the other cases, Math.round() works the same as Math.ceil(). For instance:

Math.round(-1.5)                    // result is -1


Math.round(1.8)                      // result is 2



Trigonometric functions


The sin(), cos(), and tan() methods return the sine, cosine, and tangent of an angle, respectively. In all three methods, the argument is the angle in radians. Degrees can be converted to radians by using Math.toRadians(). For instance:

x = Math.sin(Math.toRadians(90.0));              // returns 1.0


The sqrt() function returns the square root of an argument of type double. For instance:

x = Math.sqrt(25.0);                      // returns 5.0


If you pass a negative number to the sqrt() function, it returns NaN ("Not a Number").

No comments:

Post a Comment