Why are there no byte or short literals in Java?

前端 未结 4 1752
盖世英雄少女心
盖世英雄少女心 2020-12-05 17:11

I can create a literal long by appending an L to the value; why can\'t I create a literal short or byte in some similar way? Why do I need to use an int literal with a cast?

相关标签:
4条回答
  • 2020-12-05 17:29

    Another reason might be that the JVM doesn't know about short and byte. All calculations and storing is done with ints, longs, floats and doubles inside the JVM.

    0 讨论(0)
  • 2020-12-05 17:41

    In C, int at least was meant to have the "natural" word size of the CPU and long was probably meant to be the "larger natural" word size (not sure in that last part, but it would also explain why int and long have the same size on x86).

    Now, my guess is: for int and long, there's a natural representation that fits exactly into the machine's registers. On most CPUs however, the smaller types byte and short would have to be padded to an int anyway before being used. If that's the case, you can as well have a cast.

    0 讨论(0)
  • 2020-12-05 17:45

    I suspect it's a case of "don't add anything to the language unless it really adds value" - and it was seen as adding sufficiently little value to not be worth it. As you've said, it's easy to get round, and frankly it's rarely necessary anyway (only for disambiguation).

    The same is true in C#, and I've never particularly missed it in either language. What I do miss in Java is an unsigned byte type :)

    0 讨论(0)
  • 2020-12-05 17:46

    There are several things to consider.

    1) As discussed above the JVM has no notion of byte or short types. Generally these types are not used in computation at the JVM level; so one can think there would be less use of these literals.

    2) For initialization of byte and short variables, if the int expression is constant and in the allowed range of the type it is implicitly cast to the target type.

    3) One can always cast the literal, ex (short)10

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