Java Reference
In-Depth Information
considered narrowing conversions, because the sign bit is incorporated into the
new character value. Since a character value is unsigned, a negative integer will
be converted into a character that has no particular relationship to the numeric
value of the original integer.
Note that boolean values are not mentioned in either widening or narrowing
conversions. A boolean value cannot be converted to any other primitive type
and vice versa.
Conversion Techniques
In Java, conversions can occur in three ways:
assignment conversion
promotion
casting
Assignment conversion occurs when a value of one type is assigned to a vari-
able of another type during which the value is converted to the new type. Only
widening conversions can be accomplished through assignment. For example,
if money is a float variable and dollars is an int variable, then the following
assignment statement automatically converts the value in dollars to a float :
money = dollars;
Therefore, if dollars contains the value 25 , after the assignment, money con-
tains the value 25.0 . However, if we attempt to assign money to dollars , the
compiler will issue an error message alerting us to the fact that we are attempting
a narrowing conversion that could lose information. If we really want to do this
assignment, we have to make the conversion explicit by using a cast.
Conversion via promotion occurs automatically when certain operators need
to modify their operands in order to perform the operation. For example, when
a floating point value called sum is divided by an integer value called count , the
value of count is promoted to a floating point value automatically, before the
division takes place, producing a floating point result:
result = sum / count;
A similar conversion is taking place when a number is concatenated with a
string. The number is first converted (promoted) to a string, then the two strings
are concatenated.
Casting is the most general form of conversion in Java. If a conversion can be
accomplished at all in a Java program, it can be accomplished using a cast. A cast
is a Java operator that is specified by a type name in parentheses. It is placed in
 
Search WWH ::




Custom Search