Java Reference
In-Depth Information
A totally fruity program
Average fruit is Infinity
The value
Infinity
indicates a positive but effectively infinite result, in that it represents a value that is
greater than the largest number that can be stored as type
double
. An effectively infinite result that was neg-
ative would be output as
-Infinity
. You don't actually need to divide by zero to produce this effect; any
calculation that generates a value that exceeds the maximum value that can be represented as type
double
has the same effect. For example, repeatedly dividing by a very small number, such as 1.0E-300, yields an
out-of-range result.
If you want to see what an indeterminate result looks like, you can replace the statement to calculate
av-
erageFruit
with the following:
averageFruit = (numOranges - 5.0)/(numApples - 10.0);
This statement doesn't make much sense, but it produces an indeterminate result. The value of
aver-
ageFruit
is output as
NaN
. This value is referred to as
Not-a-Number
, indicating an indeterminate value.
A variable with an indeterminate value contaminates any subsequent expression in which it is used, so any
operation involving an operand value of
NaN
produces the same result of
NaN
.
A value that is
Infinity
or
-Infinity
is unchanged when you add, subtract, or multiply by finite values,
but if you divide any finite value by
Infinity
or
-Infinity
the result is zero.
NOTE
If a floating-point operation results in a negative value that is so small it cannot be
represented, the result is
−
0.0. Although
−
0.0 is considered to be numerically identical to 0.0,
dividing a positive value by
−
0.0 produces
-Infinity
whereas dividing a positive value by
0.0 produces
Infinity
.
Mixed Arithmetic Expressions
You have probably guessed from earlier discussions that you can mix values of the basic types together in
a single expression. The way mixed expressions are treated is governed by some simple rules that apply to
each operator in such an expression. The rules, in the sequence in which they are checked, follow:
1.
If either operand is of type
double
, the other is converted to
double
before the operation is carried
out.
2.
If either operand is of type
float
, the other is converted to
float
before the operation is carried out.
3.
If either operand is of type
long
, the other is converted to
long
before the operation is carried out.
The first rule in the sequence that applies to a given operation is the one that is carried out. If neither
operand is
double
,
float
, or
long
, they must be
int
,
short
, or
byte
, so they are converted to type
int
where necessary and use 32-bit arithmetic to produce the result, as you saw earlier in the chapter.
Explicit Casting