Java Reference
In-Depth Information
Here is a breakdown of what this code does:
1. The first time through the outer while loop on line 20, row equals 'A' and it is printed
on line 21 and incremented to 'B' . i equals 1 during the first iteration of the inner
loop. Line 23 and 25 are false, so line 29 executes and '1' is printed.
2. When i equals 2 , line 23 is true and the continue statement on line 24 executes.
Because it is an unlabeled continue , it applies to the for loop, so control jumps to the
update statement i++ and i now equals 3 .
3. When i equals 3 , line 25 is true, a newline is printed and the continue statement on
line 27 executes. This continue refers to the while loop, so control jumps to the bool-
ean expression on line 20.
4. row equals 'B' the second time through the outer loop and is printed on line 21. The
inner loop behaves the same, printing only '1' because of the continue statements.
5. When row equals 'C' and row equals 'D' , the result is similar.
Therefore, the output of this code is
A1
B1
C1
D1
Line 24 of this example could have been clearer if we had used a label on the for loop
on line 22, but I wanted to demonstrate that it wasn't required.
We now turn our attention to two other aspects of Java that affect fl ow control:
assertions and exceptions.
Overview of Assertions
The exam objectives state that you should be able to “develop code that makes use of
assertions, and distinguish appropriate from inappropriate uses of assertions.” This section
addresses these objectives. An assertion in Java is a boolean expression placed at particular
points in your code where you think something should always be true. (The defi nition of
the word “assert” is to insist that something is true and to affi rm your claim with certainty.)
For example, I am certain that in the following code, the value of x is greater than 0 :
int a = 3, b = 5;
int x = a * b;
assert x > 0;
An assertion allows me to check for bugs in my code that might otherwise go unnoticed.
You can place assertions throughout your code, turn them on for testing and debugging
purposes, and then turn them off when your program is in production.
Search WWH ::




Custom Search