Why do I have to cast 0 to byte when the method argument is byte?
Why do I have to cast 0 to byte
when the method argument is byte
?
Example:
void开发者_JAVA技巧 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?
Because 0
is an int
literal, and down-casting to byte
from int
requires an explicit cast (since there is the possibility of information loss.) You don't need an explicit cast from int
to long
, since no information could be lost in that conversion.
The literal 0
is an integer, and there is no automatic cast from integer -> byte, due to a potential loss of precision. For example, (byte)1024
is 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)
Integer literals are implicitly of type int
, unless they are explicitly marked as long
through an L
suffix. There are no corresponding markers for short
or byte
.
Doesn't it discourage the usage of byte/short?
Perhaps it does, and rightfully so. There is no advantage in using individual bytes or shorts, and they often cause problems, especially since the introduction of autoboxing.
精彩评论