Can anyone confirm if this is true?
Java will turn a long % int into a long value. However it can never be greater than the modulus to it is always safe to cast it to an int.
long a =
int b =
int c = (int) (a % b); // cast is always safe.
Similarly a long % short will always be safe to cast to a short.
If true, does any one know why Java has a longer type for % than needed?
Additionally, there is a similar case for long & int (if you ignore sign extension)
For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
If Java automatically down-casted
a % bto anint, then the above code would cause anintoverflow rather than settingcto a perfectly reasonablelongvalue.This is the same reason that performing operations with a
doubleand anintwill produce adouble. It’s much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.Update
Also, after thinking more about this, I’m guessing most CPU architectures don’t have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU’s mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an
intwould add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep alongvalue for other operations (as I mention above), it really wouldn’t make sense to force the result into anintunless the developer explicitly wants it to be one.