Are there any real life uses for the Java byte primitive type?

Thorbjørn Ravn Andersen picture Thorbjørn Ravn Andersen · Jul 31, 2011 · Viewed 14.4k times · Source

For some inexplicable reason the byte primitive type is signed in Java. This mean that valid values are -128..127 instead of the usual 0..255 range representing 8 significant bits in a byte (without a sign bit).

This mean that all byte manipulation code usually does integer calculations and end up masking out the last 8 bits.

I was wondering if there is any real life scenario where the Java byte primitive type fits perfectly or if it is simply a completely useless design decision?


EDIT: The sole actual use case was a single-byte placeholder for native code. In other words, not to be manipulated as a byte inside Java code.


EDIT: I have now seen a place where an inner tight loop needed to divide by 7 (numbers 0..32) so a lookup table could be done with bytes as the datatype so the memory usage could be kept low thinking of L1 cache usage. This does not refer to the signed/unsignedness but was a case of an actual usage.

Answer

Bozho picture Bozho · Jul 31, 2011

Josh Bloch recently mentioned in a presentation that this is one of the mistakes in the language.

I think the reason behind this is that java does not have unsigned numeric types, and byte should conform to that rule. (Note: char is unsigned, but does not represent numbers)

As for the particular question: I can't think of any example. And even if there were examples, they would be fewer than the ones for 0..255, and they could be implemented using masking (rather than the majority)