Java Reference
In-Depth Information
The value
Infinity
indicates a positive but effectively infinite result, in that it is greater than the
largest number that can be represented as type
double
. A negative infinite result 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
will have
the same effect. For example, repeatedly dividing by a very small number, such as 1.0E
-
300, will yield
an out-of-range result.
If you want to see what an indeterminate result looks like, you can replace the statement to calculate
averageFruit
with:
averageFruit = (numOranges - 5.0)/(numApples - 10.0);
This statement doesn't make much sense but it will produce an indeterminate result. The value of
averageFruit
will be output as
NaN
.
This value is referred to as Not-a-Number, indicating an
indeterminate value. A variable with an indeterminate value will contaminate any subsequent
expression in which it is used, producing the same result of
NaN
.
A value that is
Infinity
or
-Infinity
will be unchanged when you add, subtract, or multiply by
finite values, but if you divide any finite value by
Infinity
or
-Infinity
the result will be zero.
Mixed Arithmetic Expressions
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, are:
If either operand is of type
double
, the other is converted to
double
before the operation is
carried out.
❑
If either operand is of type
float
, the other is converted to
float
before the operation is
carried out.
❑
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 use 32-bit arithmetic
as we saw earlier.
Explicit Casting
It may well be that the default treatment of mixed expressions listed above is not what you want. For
example, if you have a
double
variable
result
, and you compute its value using two
int
variables
three
and
two
with the values 3 and 2 respectively, with the statement:
result = 1.5 + three/two;