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 sumSuppose, 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 2Can 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
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 + yThis 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!
Basically, if it's a Java binary operator, you should be able to use a binary compound assignment operator as well.