Java Reference
In-Depth Information
In Java, the concept of a method, whether predefined or user-defined, is similar to that of
a function in algebra. For example, every method has a name and, depending on the
values specified by the user, it does some computation. This section discusses various
predefined methods.
Some of the predefined mathematical methods are
pow(x, y)
and
sqrt(x)
.
The power method,
pow(x, y)
, calculates
x
y
; that is, the value of
pow(x, y)
is
x
y
.
For example,
pow(2, 3)
is
8.0
and
pow(2.5, 3)
is
15.625
. Because the value of
pow(x, y)
is of type
double
, we say that the method
pow
is of type
double
or that the
method
pow
returns a value of type
double
. Also,
x
and
y
are called the parameters
(or arguments) of the method
pow
. The method
pow
has two parameters.
The square root method,
sqrt(x)
, calculates the nonnegative square root of
x
for
x >= 0.0
. For example,
sqrt(2.25)
is
1.5
. The method
sqrt
is of type
double
and
has only one parameter.
In Java, predefined methods are organized as a collection of classes, called class libraries.
For example, the
class
Math
contains mathematical methods. Table 7-1 lists some of
Java's predefined mathematical methods. The table gives the name of the method (in bold
type), number of parameters, the data type of the parameters, and the method type. The
method type is the data type of the value returned by the method. The table also shows
how a method works. The
class
Math
is contained in the package
java.lang
.
7
TABLE 7-1
Some Predefined Mathematical Methods and Named Constants
class
Math
(Package:
java.lang
)
Named Constants
double
E
;
E = 2.7182818284590455
double
PI
;
PI = 3.141592653589793
Methods
Expression
Description
Returns the absolute value of
x
.If
x
is of type
int
, it returns a value of
type
int
;if
x
is of type
long
, it returns a value of type
long
;if
x
is of
type
float
, it returns a value of type
float
;if
x
is of type
double
,it
returns a value of type
double
.
Example:
abs(-67)
returns the value
67
abs(35)
returns the value
35
abs(-75.38)
returns the value
75.38
abs(x)
Search WWH ::
Custom Search