Q:

Java Float to Long Typecast

Can anyone tell me what am I doing wrong here. I am able to typecast y into long, but the same doesn't work for x/y.
class Test {

long convert(int x, float y) {
    //return (long) x/y; // cannot convert from float to long
    return (long)y;
    }

}

A:

The only issue here is how things are parenthesized.  You'd be fine if you wrote
return (long) (x / y);

When you wrote (long) x / y, that was treated as ((long) x) / y, which is a float according to the typing rules of Java.

A:

Here
return (long) x/y; 

You are casting x as long but the entire expression is still float because of y and hence when you try to return it , it shows error. It is same as return ((long)x/y);
Better :
return (long) (x/y);

