Cast Double to Integer in Java

4lex1v picture 4lex1v · Feb 1, 2012 · Viewed 1M times · Source

Any way to cast java.lang.Double to java.lang.Integer?

It throws an exception

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"

Answer

anubhava picture anubhava · Feb 1, 2012

You need to explicitly get the int value using method intValue() like this:

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5

Or

double d = 5.25;
int i = (int) d;