The other answers have some good information, but unfortunately, they both promote an incorrect idea about the cast to byte.
The & 0xFF
is unnecessary in both cases in your original code.
A narrowing cast discards the high-order bits that don't fit into the narrower type. In fact, the & 0xFF
actually first causes the short to be promoted to an int
with the most significant 24 bits cleared, which is then chopped down and stuffed in a byte by the cast. See the Java Language Specification Section §5.1.3 for details.
buffer[position] = (byte) sample;
buffer[position+1] = (byte) (sample >>> 8);
Also, note my use of the right shift with zero extension, rather than sign extension. In this case, since you're immediately casting the result of the shift to a byte, it doesn't matter. In general, however, the operators give different results, and you should be deliberate in what you choose.