Java Float to Long Typecast

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; } } 
+8
java type-conversion
source share
2 answers

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.

+20
source share

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

It's better:

 return (long) (x/y); 
+2
source share

All Articles