Classes/Objects  «Prev  Next»

Lesson 5 Casting
Objective Describe how casting between numeric types and between object references occurs.

Casting Numeric Types

Java Converting Casting

Casting

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:
  1. Any object reference can be cast to a reference of class Object.
  2. An object reference can be cast to a reference of class C if the actual class of the object is a subclass of C.
  3. 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.
  4. 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.

The following link contains Java code that shows you how to cast a parent reference variable to a Child class to access a method in the child class.   Cast Parent Reference

Bitwise Operators - Exercise

Click the Exercise link below to practice analyzing code using bitwise operators.
Bitwise Operators - Exercise

Java Casting - Quiz

Click the Quiz link below to check your understanding of casting and converting.
Java Casting - Quiz