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 representin
Digitized sound (or any other signal) with 8 bit signed samples seems like the only reasonable example to me. Of course having signed bytes is no requirement to handling such signals and it can be argued whether Java byte "fits perfectly".
Personally I think not having unsigned is a mistake. Not only because there's more use for unsigned bytes/ints but because I prefer a stronger type system. It would be nice to be able to specify that negative numbers are not valid and allow compiler checks and runtime exceptions for violations.
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)
I used it frequently when I was programming software and games for J2ME. On most J2ME-devices, you have limited resources, so storing for example the map of a level in a byte-array is less resource-intensive than storing it in an int-array.
Amazingly, I just used byte
in Java for the first time last week, so I do have an (albeit unusual) use-case. I was writing a native Java function, which lets you implement a function in a library that can be called by Java. Java types need to be converted to types in the native language, in this case C
The function needed to take an array of bytes, but (forgetting about the byte
type entirely at the time) I had it take a char[]
. The signature Java generates for the C function gives the type of that parameter as jcharArray
, which can be converted to a bunch of jchar
s, which are typedef-ed in jni.h
to unsigned short
. Naturally, that is not the same size -- it's 2 bytes instead of 1. This caused all sorts of problems with the underlying code. Making the Java type byte[]
resulted in a jbyteArray
, and jbyte
on Linux is typedef-ed to signed char
, which is the right size