(^122) | Arithmetic Expressions
Method Argument Type(s) Result Type Result
Math.abs(x) int,long,float, or double same as argument absolute value of x
Math.cos(x) double double cosine ofx(xis in radians)
Math.sin(x) double double sine of x(xis in radians)
Math.log(x) double double natural logarithm of x
Math.pow(x,y) double double xraised to the power y(if x= 0.0,y
must be positive; if x≤0.0,ymust be
a whole number)
Math.min(x,y) int,long,float, or double same as argument smaller of xand y
Math.max(x,y) int,long,float, or double same as argument larger of xand y
Math.random() none double a random number greater than or
equal to 0.0 and less than 1.0
Math.round(x) double long the argument rounded up to the
nearest integer
Math.round(x) float int the argument rounded up to the
nearest integer
Math.sqrt(x) double double square root of x(x≥0.0)
Table 3.1 MathMethods
3.7 Value-Returning Class Methods
The calls to the Mathmethods like those in Table 3.1 are value-returning class methods. For
example, the statement
rootX = Math.sqrt(x);
calls the sqrtmethod associated with the Mathclass, which returns the square root of xthat
is then assigned to rootX. The third column in Table 3.1 tells you the type of the value that is
returned by each of the Mathmethods.
Notice that these arithmetic value-returning methods (such as Math.absand Math.sqrt)
are called with the name of their class rather than the name of a specific object. Recall from
Chapter 2 that methods can be instance methods or class methods. The Mathmethods are
class methods because they are associated with the class itself rather than a particular in-
stance of the class. They belong to the class java.lang.Math, which is automatically imported
into every application by the Java compiler.
In Chapter 2, we saw how easy it is to write our own value-returning instance methods.
Value-returning class methods are just as easy to write. For example, suppose we want to write