Page 113 - Introduction to Programming with Java: A Problem Solving Approach
P. 113
3.17 More Operators: Increment, Decrement, and Compound Assignment 79 Increment and Decrement Operators
It’s fairly common for a computer program to count the number of times something occurs. For example, have you ever seen a Web page that displays the number of “visitors”? The number of visitors is tracked by a program that counts the number of times the Web page has been loaded on someone’s Web browser. Since counting is such a common task for programs, there are special operators for counting. The increment op- erator (++) counts up by 1. The decrement operator (--) counts down by 1.
Here’s one way to increment the variable x:
x = x + 1;
And here’s how to do it using the increment operator: x++;
The two techniques are equivalent in terms of their functionality. Experienced Java programmers al- most always use the second form rather than the first form. And proper style suggests using the second form. So use the second form.
Here’s one way to decrement the variable x:
x = x - 1;
And here’s how to do it using the decrement operator: x--;
Once again, you should use the second form.
Apago PDF Enhancer
Compound Assignment Operators
Let’s now discuss five of Java’s compound assignment operators: +=, -=, *=, /=, and %=.
The += operator updates a variable by adding a specified value to the variable. Here’s one way to incre-
ment x by 3:
x = x + 3;
And here’s how to do it using the += operator: x += 3;
The two techniques are equivalent in terms of their functionality. Experienced Java pro- grammers almost always use the shorter second form rather than the longer first form. And proper style suggests using the second form. So use the second form.
The -= operator updates a variable by subtracting a specified value from the variable. Here’s one way to decrement + by 3:
x = x - 3;
And here’s how to do it using the -= operator: x -= 3;
Once again, you should use the second form.
Look for shortcuts.