Java Operators - Doing More Math with Assignment Operators
(Page 3 of 4 )
Below is a list of Assignment and Arithmetic Assignment Operators and what they do:
Operator | What it Does |
+ | For addition |
- | For subtraction |
* | For multiplication |
/ | For division |
% | For modulation |
++ | For incrementing |
-- | For decrementing |
+= | For addition assignments |
-= | For subtraction assignments |
*= | For multiplication assignments |
/= | For divisional assignments |
%= | For modulus assignments |
If you want to incrementally increase a number, you can do so this way:
my_weight = 4000;
my_weight++;
This would increase my weight from 4000 to 4001. If I stood up, lifting my enormous body, I could adjust my weight this way:
my_weight = 4001;
my_weight--;
Now my weight is back down to a fearsome 4000. Soon you won't be able to see me when I turn sideways. Dealing with increments/decrements can get tricky for some people, but not us with our enormous brains. The reason they can become tricky is because of operator precedence. Observe the following two coding samples:
my_weight = 4000;
my_new_weight = ++my_weight;
The above would result in my weight being 4001. This is because the ++ takes precedence, adding 1 to my weight before adding my_weight to my_new_weight. If I had placed the ++ on the opposite side of my_weight I would have received a different result.
my_weight = 4000;
my_new_weight = my_weight++;
This would result in my_new_weight carrying the value 4000. This is because it adds the value of my_weight to my_new_weight prior to adding 1 to the value of my_weight.
Next: Forming a Relationship with Operators >>
More Java Articles
More By James Payne