How are integers cast to bytes in Java?

Solution 1:

This is called a narrowing primitive conversion. According to the spec:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

So it's the second option you listed (directly copying the last 8 bits).

I am unsure from your question whether or not you are aware of how signed integral values are represented, so just to be safe I'll point out that the byte value 1111 1111 is equal to -1 in the two's complement system (which Java uses).

Solution 2:

or does it just directly copy the last 8 bits of the integer

yes, this is the way this casting works

Solution 3:

int i = 255;

byte b = (byte)i;

So the value of be in hex is 0xFF but the decimal value will be -1.

int i = 0xff00;

byte b = (byte)i;

The value of b now is 0x00. This shows that java takes the last byte of the integer. ie. the last 8 bits but this is signed.