Why do I have to cast 0 to byte when the method argument is byte?
Example:
void foo() {
bar((byte) 0);
}
void bar(byte val) {}
I know that if the argument is of type long I don’t have to cast it, so I’m guessing that Java thinks of mathematical integers as integers runtime.
Doesn’t it discourage the usage of byte/short?
The literal
0is an integer, and there is no automatic cast from integer -> byte, due to a potential loss of precision. For example,(byte)1024is outside the valid range. Perhaps the compiler could be smarter and allow this for small integer literals, but it doesn’t…Widening to long is okay, since every integer can be a long with no loss of information.
And yes, for this reason I would almost never use short or byte in any APIs exposed by my code (although it would be fine for intermediate calculations)