Assignment operators

Figure 167. The += operator Slide presentation Create comment in forum

Increment variable by right hand value:

int a = 4;

a = a + 2;

System.out.println("Value:" + a);
int a = 4;

a += 2;

System.out.println("Value:" + a);
Value:6

Figure 168. The &= operator Slide presentation Create comment in forum

Logical and operation:

boolean examSuccess = true,
        registered = false;

examSuccess = examSuccess & registered;

System.out.println(
  "Exam success:" + examSuccess);
boolean examSuccess = true,
        registered = false;

examSuccess &= registered;

System.out.println(
  "Exam success:" + examSuccess);
Exam success:false

Figure 169. Assignment operators #1 / 2 Slide presentation Create comment in forum
= Assign right to left operand
+= Assign sum of operands to left operand
-= Assign difference of operands to left operand
*= Assign product of operands to left operand
/= Assign quotient of operands to left operand

Figure 170. Assignment operators #2 / 2 Slide presentation Create comment in forum
%= Assign remainder of operands to left operand
&= Assign logical and of operands to left operand
|= Assign logical or of operands to left operand

exercise No. 53

Understanding += Create comment in forum

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;

A:

According to Figure 163, “No binary + operator yielding byte the arithmetic + operator acting any two non-long values will always return a result of type int. Thus the expression age + 2 of type int can only be assigned to a variable age of type byte when using a cast:

byte age = 80;

age = (byte)(age + 2);

On contrary the operator += will accept any right hand integer value (even of type long!) thereby 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, the latter being a byte's number of different representable values.