How to specify a constant is a byte or short?

前端 未结 3 1056
轮回少年
轮回少年 2021-01-11 13:01

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-mism

相关标签:
3条回答
  • 2021-01-11 13:48

    For example:

    public static final byte CURRENCY_SYMBOL = 26;
    
    public static final short MAX_VALUE = 3276;
    
    0 讨论(0)
  • 2021-01-11 13:54

    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.

    0 讨论(0)
  • 2021-01-11 13:59

    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.

    0 讨论(0)
提交回复
热议问题