Type conflict

exercise No. 222

Q:

We consider:

byte divideByThree(final byte value) {
  return value / 3;   // Compile Error: Incompatible types.
                      // Required: byte
                      // Found: int
}

Using a cast solves our problem syntactically:

byte divideByThree(final byte value) {
  return (byte)(value / 3);
}

Answer the following questions:

  1. Why does the compile time error happen in the first place?

  2. Casts may have negative effects i.e. truncation problems. May this become a problem with respect to the second code snippet?

A:

  1. According to Binary operator type examples the value / 3 expression is of type int rather then byte. This contradicts the method's return type of byte causing the compile time error.

  2. Dividing any value by three always stays within a given type's range. For example 127 / 3 equals 42 and -128 / 3 equals -42. Casting the value / 3 expression into a byte is thus a safe operation guaranteed to avoid any data truncation problems.