### Assignment operators

No. 52

#### Understanding +=

Q:

Consider the following snippet:

byte age = 80;

age += 2;

This will compile and execute thereby incrementing the age variable's value by 2 as expected. The seemingly equivalent code however will not even compile:

byte age = 80;

age = age + 2; // Error: Incompatible types.
// Required: byte
// Found: int

On the other hand the += operator even accepts values exceeding a byte's upper range limit of 127:

byte age = 80;

age += 200;

### Tip

A:

According to Figure 117, “No binary + operator yielding byte the arithmetic + operator acting any two non-long values will always return a result of type int. The expression age + 2 is thus of type int and therefore requires a cast when being assigned to our variable age of type byte:

byte age = 80;

age = (byte)(age + 2);

### Note

Since age is not being defined as final the value of the expression age + 2 is not being known at compile time. Adding final allows for compile time evaluation and thus assignment to a second variable of type byte without requiring a cast:

final byte age = 80;         // Value cannot be altered.

byte gettingOlder = age + 2; // o.K. without cast: age + 2 can be evaluated at compile time.

On contrary the operator += will accept any right hand integer value (even of type long!) thereby possibly cycling through the range of byte values e.g.:

Code Execution result
byte age = 80;
age += 200;
System.out.println("Age:" + age);
Age:24

Notice 24 being equal to 80 + 200 - 256 with 256 being a byte's number of different representable values.