A byte
in java is a signed 8-bit value. 8 bits gives you 256 possible values, but since a byte
is signed and can represent positive and negative values, those 256 values must be roughly split in half across the possible positive and negative values. So you can't store negative values past -128; in particular don't expect to be able to store -256
.
What you're actually observing when your byte has the value 127
is known as overflow (see this wiki article)
If you need to manipulate values outside this range, as in your example code, or e.g. an unsigned byte, at some point you'll need to make use of a wider integer type, like short
.
The standard libraries provide these limits as Byte.MIN_VALUE
and Byte.MAX_VALUE
(docs here and here).