Why are there no byte or short literals in Java?

2019-01-14 10:35发布

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?

And if the answer is "Because there was no short literal in C", then why are there no short literals in C?

This doesn't actually affect my life in any meaningful way; it's easy enough to write (short) 0 instead of 0S or something. But the inconsistency makes me curious; it's one of those things that bother you when you're up late at night. Someone at some point made a design decision to make it possible to enter literals for some of the primitive types, but not for all of them. Why?

4条回答
Rolldiameter
2楼-- · 2019-01-14 10:52

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.

查看更多
干净又极端
3楼-- · 2019-01-14 10:56

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

查看更多
Bombasti
4楼-- · 2019-01-14 11:02

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 :)

查看更多
可以哭但决不认输i
5楼-- · 2019-01-14 11:04

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.

查看更多
登录 后发表回答