The cast operator
(type)
is used to convert numeric values from one numeric primitive type to another, or to change an object reference to a compatible type.
When a numeric primitive type is cast, and the resulting value is too large to fit in the size of the destination type, the high order bytes are discarded.
The
Cast1 program provides an example of numeric casting.
When an object reference is cast from one type to another, the following rules apply:
- Any object reference can be cast to a reference of class
Object
.
- An object reference can be cast to a reference of class C if the actual class of the object is a subclass of C.
- An object reference can be cast to a reference of interface I, if the object implements I, is a subinterface of I, or if the object is an array and I is the
Cloneable
interface.
- An object reference can be cast to a reference of an array type (with element reference type T') if the object is an array (with element reference type T) such that T can be cast into T'.
The
Cast2 program illustrates the use of casting with
String
and
Object
objects.