Java Reference
In-Depth Information
Method arguments may be constants, variables or expressions. If
c
=
13.0
,
d
=
3.0
and
f=4.0
, then the statement
System.out.println(Math.sqrt(c + d * f));
calculates and prints the square root of
13.0
+
3.0
*
4.0
=
25.0
—namely,
5.0
. Figure 6.2
summarizes several
Math
class methods. In the figure,
x
and
y
are of type
double
.
Method
Description
Example
abs(
x
)
absolute value of
x
abs(
23.7
)
is
23.7
abs(
0.0
)
is
0.0
abs(
-23.7
)
is
23.7
ceil(
x
)
rounds
x
to the smallest integer not
less than
x
ceil(
9.2
)
is
10.0
ceil(
-9.8
)
is
-9.0
cos(
x
)
trigonometric cosine of
x
(
x
in radians)
cos(
0.0
)
is
1.0
exponential method
e
x
exp(
x
)
exp(
1.0
)
is
2.71828
exp(
2.0
)
is
7.38906
floor(
x
)
rounds
x
to the largest integer not
greater than
x
floor(
9.2
)
is
9.0
floor(
-9.8
)
is
-10.0
log(
x
)
natural logarithm of
x
(base
e
)
log(
Math.E
)
is
1.0
log(
Math.E
*
Math.E
)
is
2.0
max(
x
,
y
)
larger value of
x
and
y
max(
2.3
,
12.7
)
is
12.7
max(
-2.3
,
-12.7
)
is
-2.3
min(
x
,
y
)
smaller value of
x
and
y
min(
2.3
,
12.7
)
is
2.3
min(
-2.3
,
-12.7
)
is
-12.7
x
raised to the power
y
(i.e.,
x
y
)
pow(
x
,
y
)
pow(
2.0
,
7.0
)
is
128.0
pow(
9.0
,
0.5
)
is
3.0
sin(
x
)
trigonometric sine of
x
(
x
in radians)
sin(
0.0
)
is
0.0
sqrt(
x
)
square root of
x
sqrt(
900.0
)
is
30.0
tan(
x
)
trigonometric tangent of
x
(
x
in radians)
tan(
0.0
)
is
0.0
Fig. 6.2
|
Math
class methods.
static
Variables
Recall from Section 3.2 that each object of a class maintains its
own
copy of every instance
variable of the class. There are variables for which each object of a class does
not
need its
own separate copy (as you'll see momentarily). Such variables are declared
static
and are
also known as
class variables
. When objects of a class containing
static
variables are cre-
ated, all the objects of that class share
one
copy of those variables. Together a class's
static
variables and instance variables are known as its
fields
. You'll learn more about
static
fields in Section 8.11.
Math
Class
static
Constants
PI
and
E
Class
Math
declares two constants,
Math.PI
and
Math.E
, that represent
high-precision ap-
proximations
to commonly used mathematical constants.
Math.PI
(3.141592653589793)
is the ratio of a circle's circumference to its diameter.
Math.E
(2.718281828459045) is the