ClassCastException, casting Integer to Double

Khuba picture Khuba · Apr 6, 2011 · Viewed 147.7k times · Source
ArrayList marks = new ArrayList();
Double sum = 0.0;
sum = ((Double)marks.get(i));

Everytime I try to run my program, I get a ClassCastException that states: java.lang.Integer cannot be cast to java.lang.Double

Answer

Andreas Dolk picture Andreas Dolk · Apr 6, 2011

We can cast an int to a double but we can't do the same with the wrapper classes Integer and Double:

 int     a = 1;
 Integer b = 1;   // inboxing, requires Java 1.5+

 double  c = (double) a;   // OK
 Double  d = (Double) b;   // No way.

This shows the compile time error that corresponds to your runtime exception.