Why are there no bytes or short literals in Java?

I can create a literal number by adding L to the value; why can't I create a literal short or byte in some other way? Why do I need to use a literal int literal?

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

It does not affect my life in any meaningful way; it's easy enough to write (short) 0 instead of 0S or something else. But the inconsistency makes me curious; this is one of those things that bother you when you are late at night. Someone at some point made a design decision that allowed us to introduce literals for some primitive types, but not for all of them. Why?

+53
java primitive
Nov 25 '08 at 15:57
source share
4 answers

In C, int should at least be the “natural” word size of the processor, and long should probably be the “big natural” word size (not sure about this last part, but it also explains why int and long have the same size on x86).

Now, I assume that for int and long there is a natural representation that exactly matches machine registers. However, for most processors, the smaller byte and short types had to be padded to int anyway before use. If so, you can also roll.

+15
Nov 25 '08 at 16:09
source share

I suspect that this is a case of “do not add anything to the language unless it really adds value” - and this was considered to be adding a sufficiently small value to not be worth it. As you said, it’s easy to get around, and frankly, it is rarely necessary in any case (only to eliminate ambiguity).

The same is true in C #, and I never really missed it in any of the languages. What I missed in Java is the unsigned byte type :)

+8
Nov 25 '08 at 16:02
source share

Another reason may be that the JVM is not aware of short and byte. All calculations and storage are done using ints, longs, floats and double in the JVM.

+5
Nov 25 '08 at 16:04
source share

There are a few things to consider.

1) As discussed above, the JVM does not have the concept of bytes or short types. Typically, these types are not used in JVM computing; therefore, you might think that the use of these literals will be less.

2) To initialize bytes and short variables, if the int-expression is constant and in the allowed range of this type it is implicitly cast to the target type.

3) You can always use a literal, ex (short) 10

+2
Feb 26 '13 at 20:23
source share



All Articles