Type assignment problem

exercise No. 252

Q:

Consider the following code snippet:

byte a, b;
...
byte average = (a + b) / 2;
  1. The compiler complains Required type: byte Provided: int with respect to the second line. Why is that although only byte values are being involved?

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

A:

  1. An expression byte + byte is of type int, see Binary operator type examples.

  2. We require a 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 arithmetic overflow errors cannot occur.