For the long data type, I can suffix a number with L to make the compiler know it is long. How about byte and short?
As motivation, the following yields a type-mismatch error:
List<Short> a = Arrays.asList(1, 2, 3, 4);
What you are actually talking about is an integer literal ( 1
) versus a long literal ( 1L
). There is actually no such thing as a short or byte literal in Java. But it usually doesn't matter, because there is an implicit conversion from integer literals to the types byte
, short
and char
. Thus:
final byte one = 1; // no typecast required.
The implicit conversion is only allowed if the literal is in the required range. If it isn't you need a type cast; e.g.
final byte minusOne = (byte) 255; // the true range of byte is -128 .. +127
There are other cases where an explicit conversion is needed; e.g. to disambiguate method overloads, or to force a specific interpretation in an expression. In such cases you need to use a cast to do the conversion.
Your example is another of those cases.
But the bottom line is that there is no Java syntax for expressing byte
or short
literals.
It's done automatically for you at the point of use
If an int literal is assigned to a short or a byte and it's value is within legal range, the literal is assumed to be a short or a byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With