tags:

views:

564

answers:

3

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?

+1  A: 

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

Jon Skeet
yes, please add unsigned byte :( . for the issue at hand, i think it's worth to mention there is a long iteral because an int literal cannot represent all values of a long. But an int can represent all values of a short on the other hand.
Johannes Schaub - litb
+2  A: 

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.

Joachim Sauer
Okay, but is that true of every JVM? And even if it is, should the language definition really be dependent on implementation details of the VM it runs on? Shouldn't that be the other way around?
Will Wagner
It's part of the JVM spec, so yes: the JVM has no way of knowing what type the value it handles really is. (Except for some operations such as array access, where separate opcodes exist).
Joachim Sauer
Storing *isn't* always done with ints etc. The obvious example is an array of bytes, which is certainly stored as an array of bytes rather than ints. See also http://stackoverflow.com/questions/229886/size-of-a-byte-in-memory-java
Jon Skeet
Right, arrays are a special case that *do* have per-type instructions (probably because byte[] that used 4 byte per entry would be a tiny bit too wasteful)
Joachim Sauer
+2  A: 

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.

efficientjelly