ncst
ncst

Reputation: 187

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;
    }

}

Upvotes: 11

Views: 41057

Answers (2)

AllTooSir
AllTooSir

Reputation: 49372

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);

Upvotes: 4

Louis Wasserman
Louis Wasserman

Reputation: 198103

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.

Upvotes: 25

Related Questions