Incremental Java
Incremental Java Compound Assignment Statements Scenerio Suppose you had an int variable, sum, and you wanted to add 10 to it. How would you do this? Here's one solution:
sum = sum + 10 ;
This kind of operation is very common (where 10 is replaced by whatever value you want). It's so common that Java has a shorter way of saying the same thing. Java uses the compound addition assignment operator, which looks like: += (plus sign, followed by equal sign).
sum += 10 ; // Add 10 to sum
Suppose, instead of adding a value to sum, you wanted to double it? That is, you wanted to multiply it by 2? One way to do this is:
sum = sum * 2 ; // Multiply sum by 2
Can you guess the shortcut? If += lets you add the value on the RHS to the LHS, what do you think the operator is for multiplying the value from the RHS to the LHS? Yes, it's *=.
sum *= 2 ; // Multiply sum by 2
Binary Operators to Binary Assignment Operators Nearly every binary operator can be made into a compound assignment operator. For example, suppose Java has a binary operator @ (it doesn't, but pretend that it does). Java is very likely to have a binary assignment operator @=. Here's the semantics.
lvalue @= rvalue ;
is the same as:
lvalue = lvalue @ (rvalue) ;
Notice that parentheses are added to the rvalue. This is necessary to avoid problems with precedence. For example, consider:
x *= 3 + y
This is equivalent to:
x = x * ( 3 + y ) ;
If we didn't put the parentheses, we'd get:
x = x * 3 + y ; // WRONG!
which, using Java's rule of precedence, would be equivalent
x = ( x * 3 ) + y ; // WRONG!
and give us a different answer from
x = x * ( 3 + y ) ; // RIGHT!
Some Compound Assignment Operators Many Java programmers are unaware of how many different compound assignment operators there are. Here's a partial list: +=, *=, /=, -=, %=, &=, &&=, |=, ||=, <<=, >>=, ^=. Basically, if it's a Java binary operator, you should be able to use a binary compound assignment operator as well.