15

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);
interestedparty333
  • 2,386
  • 1
  • 21
  • 35
user705414
  • 20,472
  • 39
  • 112
  • 155

3 Answers3

19

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
5

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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
1

For example:

public static final byte CURRENCY_SYMBOL = 26;

public static final short MAX_VALUE = 3276;
JuanZe
  • 8,007
  • 44
  • 58