By Alvin Alexander. Last updated: June 4, 2016
Java exceptions FAQ: What is a Java ClassCastException?
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another. Here’s an example Java program which throws a ClassCastException intentionally:
package com.devdaily.javasamples;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ClassCastExceptionExample {
public ClassCastExceptionExample() {
List list = new ArrayList();
list.add("one");
// ... some time later
Iterator it = list.iterator();
while (it.hasNext()) {
// intentionally throw a ClassCastException by trying to cast a String to an
// Integer (technically this is casting an Object to an Integer, where the Object
// is really a reference to a String:
Integer i = (Integer)it.next();
}
}
public static void main(String[] args) {
new ClassCastExceptionExample();
}
}
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
Exception in thread "main" java.lang.ClassCastException: java.lang.String at com.devdaily.javasamples.ClassCastExceptionExample.(ClassCastExceptionExample.java:25) at com.devdaily.javasamples.ClassCastExceptionExample.main(ClassCastExceptionExample.java:31)
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

