Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a constant is a byte or short?

Tags:

java

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);
like image 608
user705414 Avatar asked Jan 14 '12 08:01

user705414


2 Answers

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.

like image 184
Stephen C Avatar answered Oct 11 '22 02:10

Stephen C


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.

like image 30
Joachim Isaksson Avatar answered Oct 11 '22 03:10

Joachim Isaksson