5
C H A P T E R
Conversions and Promotions
Thou art not for the fashion of these times,
Where none will sweat but for promotion.
William Shakespeare,
As You Like It
, Act II, scene iii
E
VERY Java expression has a type that can be deduced from the structure of the
expression and the types of the literals, variables, and methods mentioned 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; for example, if the expression in an
if
statement ( 14.8) has any
type other than
boolean
, a compile time error occurs. In other cases, the context
may be able to accept a type that is related to the type of the expression; as a con
venience, rather than requiring the programmer to indicate a type conversion
explicitly, the Java 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 action 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
. For example:
A conversion from type
Object
( 20.1) to type
Thread
( 20.20) 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.
51
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved