Java Reference
In-Depth Information
The variables x and y are parameters and get their values from the call to the
method. Many calls are possible, so we don't really know anything about the values of
x and y . Thus, the assertion x > y could be true but doesn't have to be. The assertion
is sometimes true, sometimes false at point A. Likewise, the assertion x == y could
be true depending on what values are passed to the method, but it doesn't have to be
true. However, we initialize the local variable z to 0 just before point A, so the asser-
tion z == 0 will always be true at that point in execution. So, we can fill in the first
line of the table as follows:
x > y
x == y
z == 0
Point A
sometimes
sometimes
always
Point B appears just inside the while loop:
while (x != y) {
// Point B
z++;
...
}
We get to point B only by entering the loop, which means that the loop test must
have evaluated to true . In other words, at point B it will always be true that x is not
equal to y , so the assertion x == y will never be true at that point. But we don't
know which of the two is larger. Therefore, the assertion x > y is sometimes true
and sometimes false.
You might think that the assertion z == 0 would always be true at point B because
we were at point A just before we were at point B, but that is not the right answer.
Remember that point B is inside a while loop. On the first iteration of the loop we
will have been at point A just before reaching point B, but on later iterations of the
loop we will have been inside the loop just before reaching point B. And if you look at
the line of code just after point B, you will see that it increments z . There are no other
modifications to the variable z inside the loop. Therefore, each time the body of the
loop executes, z will increase by 1. So, z will be 0 at point A the first time through the
loop, but it will be 1 on the second iteration, 2 on the third iteration, and so forth.
Therefore, the right answer for the assertion z == 0 at point B is that it is sometimes
true, sometimes false. So, the second line of the table should look like this:
x > y
x == y
z == 0
sometimes
never
sometimes
Point B
Point C is right after the increment of the variable z . There are no changes to the
values of x and y between point B and point C, so the same answers apply at point C
 
Search WWH ::




Custom Search