Alan Pauley Alan Pauley - 7 months ago 26
Java Question

Convert Float to Int Discrepancy

I cannot seem to figure out why I can convert a float to an int doing the following:

float a = 3;
int b = (int)a;


but when I try the following:

public class MyTestCode{
public static int Add(Object a, Object b){
int c = (int)a;
int d = (int)b;
return c + d;
}
}


...it gives the following error:

*Exception in thread "main" java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
at myTestCode.MyTestCode.Add(MyTestCode.java:15)
at ch02.ex01.Ch02Ex01.main(Ch02Ex01.java:25)
Java Result: 1*


Why can I convert from float to int in the one example, but not the other?

Answer

This is because in one case you have a primitive float and in the other you have a java.lang.Float object. To convert that object to a float, something like this should work:

public static int add(Object a, Object b){
    float c = (Float)a;
    float d = (Float)b;
    return (int)(c + d);
}

Casting back to the primitive float first should solve the issue.