Re-assigning variables

Edit on Github instead

If you're using the variable's value to set the new value, you can shorten the statement

int age = 17;
age = age + 5;              // Age = 22

to

age += 5;                    // Now, age = 22

+= is shorthand for "increment the old value of age by 5 and store the new value in age."

Java has similar assignment operators for the other operations:

OperatorMeaningx before
int x=5;
x after
+=adds and reassignsx+= 510
-=subtracts and reassignsx-= 50
*=multiplies and reassignsx*= 525
/=divides and reassignsx/= 51
%=divides and reassigns the remainderx%= 50

Suggest changes

Related links

URL Topic Source