Home Java & J2EE Page 3 - Java Operators

# Doing More Math with Assignment Operators - Java

It's been about a month or so since we finished our beginning Java series, so I'm sure you're ready for more. This time, I am going to teach you to work with operators in Java. When I am finished, you will be able to do complex mathematical equations, add one string of text to another, and build programs so powerful you will be able to put thousands of hard working Americans out of work with the push of a button.

By: James Payne
Rating:  / 21
October 22, 2007

SEARCH DEV SHED

TOOLS YOU CAN USE

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.

 >>> More Java & J2EE Articles          >>> More By James Payne