Java Reference
In-Depth Information
Converting values to types lower in the table of Fig. 6.4 will result in different values
if the lower type cannot represent the value of the higher type (e.g., the
int
value 2000000
cannot be represented as a
short
, and any floating-point number with digits after its
decimal point cannot be represented in an integer type such as
long
,
int
or
short
). There-
fore, in cases where information may be lost due to conversion, the Java compiler requires
you to use a
cast operator
(introduced in Section 4.10) to explicitly force the conversion to
occur—otherwise a compilation error occurs. This enables you to “take control” from the
compiler. You essentially say, “I know this conversion might cause loss of information, but
for my purposes here, that's fine.” Suppose method
square
calculates the square of an
integer and thus requires an
int
argument. To call
square
with a
double
argument named
doubleValue
, we would be required to write the method call as
square((
int
) doubleValue)
This method call explicitly casts (converts)
doubleValue
's value to a a temporary integer
for use in method
square
. Thus, if
doubleValue
's value is
4.5
, the method receives the
value
4
and returns
16
, not
20.25
.
Common Programming Error 6.7
Casting a primitive-type value to another primitive type may change the value if the new
type is not a valid promotion. For example, casting a floating-point value to an integer
value may introduce truncation errors (loss of the fractional part) into the result.
Type
Valid promotions
None
double
float
double
float
or
double
long
long
,
float
or
double
int
int
,
long
,
float
or
double
char
int
,
long
,
float
or
double
(but not
char
)
short
short
,
int
,
long
,
float
or
double
(but not
char
)
byte
None (
boolean
values are not considered to be
numbers in Java)
boolean
Fig. 6.4
|
Promotions allowed for primitive types.
As you've seen, Java contains many
predefined
classes that are grouped into categories of
related classes called
packages
. Together, these are known as the Java Application Pro-
gramming Interface (Java API), or the Java class library. A great strength of Java is the
Java API's thousands of classes. Some key Java API packages that we use in this topic are
described in Fig. 6.5, which represents only a small portion of the
reusable components
in
the Java API.