Java Reference
In-Depth Information
class AbsByteShort
{
static byte abs(byte b)
{
return (b < 0) ? (byte) -b : b;
}
static short abs(short s)
{
return (s < 0) ? (short) -s : s;
}
public static void main(String[] args)
{
byte b = -2;
System.out.println(abs(b)); // Output: 2
short s = -3;
System.out.println(abs(s)); // Output: 3
}
}
valuefroma
byte
toan
int
,and
-s
converts
s
'svaluefroma
short
toan
int
.In
contrast,thesecastsarenotneededwith
(b < 0)
and
(s < 0)
,whichautomatically
cast
b
's and
s
's values to an
int
before comparing them with
int
-based
0
.
Tip
Theirabsencefrom
Math
suggeststhat
byte
and
short
arenotveryusefulin
methoddeclarations.However,thesetypesareusefulwhendeclaringarrayswhoseele-
mentsstoresmallvalues(suchasabinaryfile'sbytevalues).Ifyoudeclaredanarray
of
int
or
long
tostoresuchvalues,youwouldendupwastingheapspace(andmight
even run out of memory).
WhilesearchingthroughtheJavadocumentationforthe
java.lang
package,you
will probablyencounter aclass named
StrictMath
.Apartfromalongername, this
class appears to be identical to
Math
. The differences between these classes can be
summed up as follows:
•
StrictMath
's methods return exactly the same results on all platforms. In
contrast,someof
Math
'smethodsmightreturnvaluesthatvaryeversoslightly
from platform to platform.