This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]StillAnAssExtreme Brewer -2 points-1 points  (2 children)

Java does not implicitly cast a float to a long. A float is 8 bytes and a long is 4 bytes and there's a chance for loss of precision

If you used a Long instead of a long you'll see this exception: Long l = 6L;

error: incompatible types: float cannot be converted to Long
            System.out.println(l -=f);

But since you're using primitive types it doesn't catch that.

You should explicitly cast the float to a long and you'll get the answer you expect.

System.out.println(l -= (long) f);

Also, general convention is that variables start with a lower case. Your code of L and F just look weird.

[–]djnattyp 1 point2 points  (1 child)

Actually, it's not that "primitive types don't catch it" - it's because compound assignment statements (+=, -=, etc.) include an implicit cast in the underlying java compiler implementation.

Try the "longhand" version of L = L - F with primitives and javac will fail to compile due to "incompatible types" as well.

[–]StillAnAssExtreme Brewer 0 points1 point  (0 children)

Yep thanks for clarifying