Type assignment problem

exercise No. 228

Q:

Consider the following code snippet:

byte a, b;
...
byte average = (a + b) / 2;

The compiler complains Required type: byte Provided: int with respect to the second line. Why is that although only byte values are being involved?

Propose a solution solving the issue at the same preserving the byte result type. Is your solution susceptible to overflow errors?

A:

An expression byte + byte is of type int, see Binary operator type examples. We thus require a type cast:

...
byte average = (byte) ((a + b) / 2);

The expression a + b of type int may range from -2 * 128 to 2 * 127. Dividing by 2 leaves us with a byte's range. Thus there is no arithmetic overflow to occur.