Arithmetic Assignment Operators

written by: Gabriela C. Perez; article published: year 2008, month 01;


In: Root » Computers and technology » JAVA » Arithmetic Assignment Operators

Dutch French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic Bookmark and Share this Article

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:

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.

Disclaimer

1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here.

link to this article