Java Reference
In-Depth Information
discuss how one type converts into another and what happens when statements
include a mix of variables of different types.
Converting one type of data into another must follow the rules of casting .Ifa
conversion would result in the loss of precision, as in an int type value converted
to a short , then the compiler issues an error message unless an explicit cast is
made.
To cast type A data into type B data, put the type B name in parentheses in
front of the type A data:
Aa= a - type - data;
Bb= (B) a; // cast a, which is originally type A,
// to type B
Of course, it must be “legal” to convert type A data into type B .For the primitive
types, most, but not all, conversions are legal. An example of an illegal cast would
be an attempt to cast a String object into an int . The rules for what is legal
and what is not are described below and generally follow common sense. It is
nonsensical, for example, to convert a string into an integer since the integer
primitive type cannot “hold” a string, which is not a primitive.
An example of a sensible cast is the conversion of double data to an int :
double d = 1.234;
int i = (int) d; // Cast double to int
Expressions can promote to a wider (higher precision) type without an explicit
cast. For example, an int type can convert to long without a cast, but the reverse
requires a cast:
int i = 3;
long j = i; // no cast needed
i = (int) j; // cast required
Note that a char type value can be cast to other integer types but as an unsigned
value. The boolean type is singular; it cannot be cast to anything, and nothing
can be cast to a boolean .Ifa boolean value is needed, it must be the result of
alogical expression. For example, if an integer i > 0 is considered to be true,
then a boolean value can be obtained as follows:
boolean b = (i > 0);
2.10.1 Cast rules
Table 2.2 shows to what other primitive types a given primitive data type can be
cast. The symbol C indicates that an explicit cast is required since the precision
decreases. The symbol A indicates that the precision increases so an automatic
conversion occurs without the need for an explicit cast. N indicates that the
Search WWH ::




Custom Search