Java Reference
In-Depth Information
in type
double
:
1.0 / 3.0
is
0.3333333333333333
A
double
number such as
1.564E15
has two parts: the
mantissa
, which is
the part before the
E
, and the
exponent
, which is the part after the
E
.
1. In the number
1.564E15
, the mantissa is
1.564
. Mantissas can have
about
16
digits of accuracy. So, if you write
3.14159265358979324
, it
will be rounded off to
3.141592653589793
.
2. In the number
1.564E15
, the exponent is
15
. The maximum exponent is
308
. So if you write
1E309
, Java will tell you that the exponent is too
large. If you write
1E308*10
, Java will evaluate this to
Infinity
, and
any values that are created using it as an operand are garbage.
Java has notations for referencing the smallest positive
double
value and the
largest positive
double
value. They are:
Double.MIN_VALUE
(which is
4.9E-324
)
Double.MAX_VALUE
(which is
1.7976931348623157E308)
The basic operations on
double
values are:
unary
-
(negation, as in
-(40E5 + 5.0)
)
unary
+
(non-negation, as in
+5.1
)
+
(addition, as in
5.0 + 6.0
)
-
(subtraction, as in
4.2 - 5.1
)
*
(multiplication, as in
4.0 * 6.2
)
/
(division, as in
4.5 / 3.1
)
%
(remainder:
5.1 % 2.0
, which is
1.0999999999999996
)
The last operation illustrates an important point with regard to double oper-
ations: often, they give only approximations to the real result. One would think
that
2
goes into
5.1
twice, with a remainder of
1.1
. However, a
roundoff error
occurs because there is only a finite amount of space for each number. Computer
arithmetic give only an approximation to the answer:
1.0999999999999996
.
The
double
operators have the same precedence as the corresponding
int
operators.
Lesson 6-4 dis-
cusses the fact
that
double
operations are
approximations.
1.1.3
Casting between int and double
If the operands of an operation (one of
+
,
-
,
*
,
/
,
%
) are of type
int
, the opera-
tion is an
int
operation and produces an
int
. Thus,
10 / 4
evaluates to the
int
value
2
. If the operands are of type
double
, the operation is a
double
operation
and produces a
double
. So,
5.0 * 2.2
evaluates to the
double
value
11.0
.
If one operand of the operation is an
int
and the other is a
double
, the
int
value is converted to a
double
value and a
double
operation is performed. For
example, the expression
2+3+4*5.2
is evaluated as follows:
Lesson pages
6-2 and 6-3
discuss casting
from one type
to another.
Search WWH ::
Custom Search