Java Reference
In-Depth Information
ClassCastException
A
ClassCastException
is thrown by the JVM when an object is cast to a data type
that the object is not an instance of. Note that the compiler often helps you avoid a
ClassCastException
because you cannot attempt to cast an object to an incompatible data
type. For example, the following code does not compile:
Integer x = new Integer(10);
String y = (String) x;
The reference
x
is of type
Integer
and the compiler complains about
x
being
inconvertible to a
String
. However, there are situations where the compiler is unable to
determine whether or not a cast is convertible. For example, the following statements do
compile:
Object x = new Integer(10);
String y = (String) x;
The difference here is that
x
is a reference of type
Object
, and an
Object
reference
can
be converted to a
String
reference. The code compiles, but at runtime you will have a
problem because
x
is not a
String
. Here is the stack trace generated by the previous two
lines of code:
Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot
be cast to java.lang.String
at ClassCastDemo.main(ClassCastDemo.java:6)
Avoiding a
ClassCastException
You might wonder why you would ever cast a parent reference down to one of its child
types, but this situation is actually quite common in the real world. A lot of the methods in
the Java API return Object types that need to be cast to their appropriate child class type.
The
instanceof
operator is used in Java to avoid the
ClassCastException
, as
demonstrated in the following code:
6. Object x = new Integer(10);
7. if(x instanceof String) {
8. String y = (String) x;
9. }
The cast on line 8 is avoided in this example because line 7 evaluates to
false
. We will
see the
instanceof
operator again in Chapter 6, “OO Concepts.”
Search WWH ::
Custom Search