Can someone tell me what I'm doing wrong here. I can cast y to y in long, but the same does not 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; } }
The only problem here is how things are bracketed. It would be nice if you wrote
return (long) (x / y);
When you wrote (long) x / y , it was treated as ((long) x) / y , which is a float according to Java input rules.
(long) x / y
((long) x) / y
float
Here
return (long) x/y;
You execute x as long , but the whole float expression remains float due to y and therefore when you try to return it, an error appears. It is similar to return ((long)x/y);
x
long
y
return ((long)x/y);
It's better:
return (long) (x/y);