This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes ClassCastException and inconvertible type eror Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException and inconvertible type eror" Watch "ClassCastException and inconvertible type eror" New topic
Author

ClassCastException and inconvertible type eror

Monalisa Das
Greenhorn

Joined: May 05, 2013
Posts: 11
As given in core java api the ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. ..but when we write
List lst = new ArrayList;
lst.add(1);

Iterator <String> itr = lst.iterator();
while (itr.hasNext())
{
String str = itr.next();
}
The output for this code is ClassCastException (Integer can not be casted to String )
Integer class is not parent of String class then why this exception is thrown for the code inside while loop? why not inconvertible types error was shown during compile time



Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

At compile time, the compiler doesn't know what type of objects are going to be in that List. Because you haven't told it that.

If you expected the compiler to notice that elsewhere in the code an Integer object is added to the List, then... no, the compiler doesn't look for things like that. It just looks at the declaration of the List.
Abhishk Singh
Ranch Hand

Joined: Aug 19, 2010
Posts: 45
Monalisa Das wrote:

Integer class is not parent of String class then why this exception is thrown for the code inside while loop? why not inconvertible types error was shown during compile time



Using generics can help detect such errors at compile time while working with collections.
The code using generics is as follows(for java1.7) (Although you have already used generics for the iterator) :



Here is a reference for generics.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ClassCastException and inconvertible type eror