Friday, March 30, 2007

CONVERSIONS AND PROMOTIONS

CONVERSIONS AND PROMOTIONS

INTRODUCTION:
Type conversion is a facility in the java programming language whereby expressions whose type is not appropriately specified in a context can be implicitly converted from the type specified by the programmer to a type acceptable for its surrounding context.

A specific type conversion can also be asked for by a programmer. There is need for this in some cases:
a. to cause the java machine at run-time[1] to check for the validity of the conversion.
b. to cause a translation of the run-time value of the expression into a form appropriate for the new type.

The possible set of specific conversions in the java programming language are grouped into several broad categories:
- identity conversion
- widening primitive conversion
- narrowing primitive conversion
- widening reference conversion
- narrowing reference conversion
- boxing conversion
- unboxing conversion
- capture conversion
- String conversion
- Value set conversion

There are in addition 5 conversion contexts in which the conversion of expressions may occur. Each context allows conversion in some categories noted above but not in others.

Note that the term “conversion” is also used to describe the process of choosing a specific conversion for such a context. The 5 conversion contexts are:
- Assignment conversion: converts the type of an expression to the type of a specified variable.
- Method invocation conversion: this is applied to each argument in a method or constructor invocation and except in one case, performs the same conversion that assignment conversion does.
- Casting conversion: converts the type of an expression to the type explicitly specified by a cast operator
- String conversion: allows any type to be converted to type String
- Numeric promotion: brings the operands of a numeric operator to a common type so that ann operation can be performed.

(§5.1 of the jls has an example for the conversions above that I do not want to repeat. You can get it and study. )

Footers:

[1]. A run-time type refers to the classes of the object referred to by the value of the variable or expression at run-time, assuming that the value is not null.

No comments: