Incrementing


In the incrementCount method, you coded:

 count = count + 1; 

The right-hand side of the statement is an expression whose value is one plus whatever value that count references. On execution, Java stores this new value back into the count variable.

Adding a value to a variable is a common operation, so common that Java supplies a a shortcut. The following two statements are equivalent:

 count = count + 1; count += 1; 

The second statement demonstrates compound assignment. The second statement adds the value (1) on the right hand side of the compound assignment operator (+=) to the value referenced by the variable on the left hand side (count); it then assigns this new sum back to the variable on the left hand side (count). Compound assignment works for any of the arithmetic operators. For example,

 rate *= 2; 

is analogous to:

 rate = rate * 2; 

Adding the value 1 to an integer variable, or incrementing it, is so common that there is an even shorter cut. The following line uses the increment operator to increase the value of count by one:

 ++count; 

The following line uses the decrement operator to decrease the value of count by one:

 - -count; 

You could code either of these examples with plus or minus signs after the variable to increment:

 count++; count- -; 

The results would be the same. When they are used as part of a larger expression, however, there is an important distinction between the prefix operator (when the plus or minus signs appear before the variable) and the postfix operator (when the plus or minus signs appear after the variable).

When the Java VM encounters a prefix operator, it increments the variable before it is used as part of a larger expression.

 int i = 5; assertEquals(12, ++i * 2); assertEquals(6, i); 

When the Java VM encounters a postfix operator, it increments the variable after it is used as part of a larger expression.

 int j = 5; assertEquals(10, j++ * 2); assertEquals(6, j); 

Modify the code in CourseSession to use an increment operator. Since you're incrementing count all by itself, and not as part of a larger expression, it doesn't matter whether you use a pre-increment operator or a post-increment operator.

 private static void incrementCount() {    ++count; } 

Recompile and retest (something you should have been doing all along).



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net