Hands on Testing Java: Lab #3

Experiment #13: Increment and Decrement Expressions

Do this...
Create a test-case class named Experiment13Test.

Shorter Shortcuts

Suppose that i and j are integer variables. C programmers were (and still are) so lazy that having to write any of these statements take too much time:

Two shortcut operators were added to C and were carried over to Java:

The operators ++ and -- are called the increment and decrement operators, respectively.

Prefix and Postfix

Both of the operators have two forms: the prefix form and the postfix form, depending on where the operator appears relative to its expression.

For example, the increment of i can be done either way:

As statements, they have the exactly same effect.

Do this...
Create a test method in Experiment13Test named testIncrement(), and add this code to the method:

int i = 5;
i++;
assertEquals ("incremented i", ???, i);
int j = 55;
++j;
assertEquals ("incremented j", ???, j);

Replace the ???s with appropriate values, compile, and run for a green bar.

So why in the world do we bother with prefix and postfix forms? Well, just like every other operator, including the other assignment operators, the increment and decrement operators evaluate to a value.

The rules are these:

Expression Side Effect Evaluates To
++i increments i the new value of i
i++ increments i the original value of i

Test it out.

Do this...
Modify the statements for this test method like so:

int i = 5;
assertEquals ("post increment i", ???, i++);
assertEquals ("incremented i", ???, i);
int j = 55;
assertEquals ("pre increment j", ???, ++j);
assertEquals ("incremented j", ???, j);

Replace the ???s with appropriate values, compile, and run for a green bar.

Decrement works the same way, just with subtraction, not addition.

Do this...
Create a test method testDecrement() which runs all of the same tests as testIncrement(), just using the decrement operator. Change the assertion comments as well as the expected results.

Test Count

Question #03.13.01 How many "Runs" do you have reported in the JUnit window?
To be answered in Exercise Questions/lab03.txt.

I'm getting 20.

Terminology

decrement operator, increment operator, postfix form, prefix form