Java Reference
In-Depth Information
Table 4-1 also reveals a few curiosities starting with +infinity, -infinity, +0.0, -0.0,
and NaN (Not a Number).
Java's floating-point calculations are capable of returning +infinity, -infinity, +0.0,
-0.0, and NaN because Java largely conforms to IEEE 754 ( ht-
tp://en.wikipedia.org/wiki/IEEE_754 ) ,astandardforfloating-pointcal-
culations. The following are the circumstances under which these special values arise:
• +infinity returns from attempting to divide a positive number by 0.0. For ex-
ample, System.out.println(1.0/0.0); outputs Infinity .
• -infinity returns from attempting to divide a negative number by 0.0. For ex-
ample, System.out.println(-1.0/0.0); outputs -Infinity .
• NaN returns from attempting to divide 0.0 by 0.0, attempting to calculate the
square root of a negative number, and attempting other strange operations.
For example, System.out.println(0.0/0.0); and Sys-
tem.out.println(Math.sqrt(-1.0)); each output NaN .
• +0.0 results from attempting to divide a positive number by +infinity. For ex-
ample, System.out.println(1.0/(1.0/0.0)); outputs +0.0 .
• -0.0 results from attempting to divide a negative number by +infinity. For ex-
ample, System.out.println(-1.0/(1.0/0.0)); outputs -0.0 .
Once an operation yields +infinity, -infinity, or NaN, the rest of the expression
usually equals that special value. For example, System.out.println(1.0/
0.0*20.0); outputs Infinity . Also, an expression that first yields +infinity or -
infinitymightdevolveintoNaN.Forexample, 1.0/0.0*0.0 yields+infinity( 1.0/
0.0 ) and then NaN (+infinity *0.0 ).
Another curiosity is Integer.MAX_VALUE , Integer.MIN_VALUE ,
Long.MAX_VALUE ,and Long.MIN_VALUE .Eachoftheseitemsisaprimitivetype
wrapper class constant that identifies the maximum or minimum value that can be
represented by the class's associated primitive type. (I discuss primitive type wrapper
classes later in this chapter.)
Finally,youmightwonderwhythe abs() , max() ,and min() overloadedmethods
do not include byte and short versions, as in byte abs(byte b) and short
abs(short s) . There is no need for these methods because the limited ranges of
bytesandshortintegersmakethemunsuitableincalculations.Ifyouneedsuchameth-
od, check out Listing 4-2 .
Listing 4-2. Obtaining absolute values for byte integers and short integers
Search WWH ::




Custom Search