Alan Pauley Alan Pauley - 2 years ago 122
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;
} 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(
at ch02.ex01.Ch02Ex01.main(
Java Result: 1*

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download