The following assignment operators are similar to the increment and decrement operators that we have just seen. They are used so that you do not need to enter the source variable twice when assigning a value to a variable based on its current value. The following table shows a list of arithmetic assignment operators for the arithmetic operators that we have used so far in this chapter.

Operator |
Description |
---|---|

*= |
Multiplication assignment |

/= |
Division assignment |

+= |
Addition assignment |

–= |
Subtraction assignment |

%= |
Remainder assignment |

So we can set a value to a variable and then double its current value as follows:

int number = 22; number *= 2; // all the fours, 44

In fact, it is possible to assign values to variables using the assignment operators wherever the value type is valid, even in mid-code, so to speak.

int numberA = 30; int numberB = 7; numberA /= numberB -= 4;

The last line of code first subtracts 4 from numberB, setting it to the value of 3. Then numberA, which equals 30, is divided by the new value of numberB, which now equals 3, giving numberA the value of 10, which is the result of 30 divided by 3. This conforms to the operator precedence table shown earlier.