File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException" Watch "ClassCastException" New topic


Srikkanth Mohanasundaram
Ranch Hand

Joined: Feb 07, 2007
Posts: 237
Hi all,
Most of the time my code breaks it is due to some or other ClassCastException,any precautions i should take?
Sidd Kulk
Ranch Hand

Joined: Feb 20, 2007
Posts: 152
ClassCastException generally creeps in when you try to cast an object of one type into another incompatible type. For e.g.

When you say String s = (String)(an object of StringBuffer);

The above will throw a ClassCastException.
But if an object is a type of the casted object, then it doesn't throw this exception.

// this will not throw the exception
Object o = (Object)(any kind of object);

To avoid this kind of Exception, you may use the instanceOf operator to check whether your object is castable into a particular type.

[ May 16, 2007: Message edited by: Sidd Kulk ]
Srikkanth Mohanasundaram
Ranch Hand

Joined: Feb 07, 2007
Posts: 237
Thanks for your reply

jayalal jayarathna

Joined: May 17, 2007
Posts: 4
If U want to know what is the exact class of a given objet (ob),
ob.getClass() will tell U the class name
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46383
Class casting is notoriously error-prone. Avoid it like the plague.

In Java 5 and more recent you use generics; you can specify what kind of object is allowed into a collection etc, and there is no need for class casts in the first place.
Ricky Clarkson
Ranch Hand

Joined: Jul 27, 2006
Posts: 131
Casting is for magicians, not programmers. Stop casting, and you'll stop getting exceptions from casts.
I agree. Here's the link:
subject: ClassCastException
It's not a secret anymore!