ClassCastException In Java
Chapter:
Exception Handling
Last Updated:
22-07-2016 08:06:13 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JavaClassCastException {
public JavaClassCastException() {
List list = new ArrayList();
list.add("Java");
Iterator it = list.iterator();
while (it.hasNext()) {
Integer i = (Integer) it.next();
}
}
public static void main(String[] args) {
new JavaClassCastException();
}
}
/* ............... END ............... */
Output
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at ExceptionHandling.JavaClassCastException.<init>(JavaClassCastException.java:27)
at ExceptionHandling.JavaClassCastException.main(JavaClassCastException.java:32)
Notes:
-
ClassCastException is used to indicate that the application’s code has attempted to cast a specific object to a class of which it is not an instance.
- For example, an Integer object cannot be casted to a String object.
Tags
ClassCastException, Exception, Java