Java Reference
In-Depth Information
Chapter 5. Conversions and Promotions
Every expression written in the Java programming language has a type that can be deduced
from the structure of the expression and the types of the literals, variables, and methods men-
tioned in the expression. It is possible, however, to write an expression in a context where
the type of the expression is not appropriate. In some cases, this leads to an error at compile
time. In other cases, the context may be able to accept a type that is related to the type of the
expression; as a convenience, rather than requiring the programmer to indicate a type con-
version explicitly, the Java programming language performs an implicit conversion from the
type of the expression to a type acceptable for its surrounding context.
A specific conversion from type S to type T allows an expression of type S to be treated at
compile time as if it had type T instead. In some cases this will require a corresponding ac-
tion at run time to check the validity of the conversion or to translate the run-time value of
the expression into a form appropriate for the new type T .
Example 5.0-1. Conversions at Compile Time and Run Time
• A conversion from type Object to type Thread requires a run-time check to make sure
that the run-time value is actually an instance of class Thread or one of its subclasses;
if it is not, an exception is thrown.
• A conversion from type Thread to type Object requires no run-time action; Thread is a
subclass of Object , so any reference produced by an expression of type Thread is a
valid reference value of type Object .
• A conversion from type int to type long requires run-time sign-extension of a 32-bit
integer value to the 64-bit long representation. No information is lost.
• A conversion from type double to type long requires a nontrivial translation from a
64-bit floating-point value to the 64-bit integer representation. Depending on the ac-
tual run-time value, information may be lost.
In every conversion context, only certain specific conversions are permitted. For conveni-
ence of description, the specific conversions that are possible in the Java programming lan-
guage are grouped into several broad categories:
• Identity conversions
• Widening primitive conversions
• Narrowing primitive conversions
Search WWH ::




Custom Search