Java Reference
In-Depth Information
The program works in exactly the same way as before. The labeled break ends the loop operation beginning
with the label OuterLoop , and so effectively branches to the point indicated by the comment.
Of course, in this instance its effect is no different from that of an unlabeled break. However, in general
this would work wherever the labeled break statement was within OuterLoop . For instance, it could be
nested inside another inner loop, and its effect would be just the same - control would be transferred to
the statement following the end of OuterLoop . The following code fragment illustrates this sort of
situation. Our label this time is Outside :
Outside:
for(int i = 0 ; i< count1 ; i++) {
...
for(int j = 0 ; j< count2 ; j++) {
...
for(int k = 0 ; k< count3 ; k++) {
...
break Outside;
...
}
}
}
// The labeled break transfers to here...
The labeled break is not needed very often, but when you need to break out of a deeply nested set of
loops it can be invaluable since it makes it a simple operation.
Assertions
Every so often you will find that the logic in your code leads to some logical condition that should
always be true. If you test an integer and establish that it is odd, it is certainly true that it cannot be even
for instance. You may also find yourself writing a statement or statements that, although they could be
executed in theory, in practice they never really should be. I don't mean by this the usual sorts of errors
that occur such as some incorrect data has been read in somehow. This should be handled ordinarily by
the normal code. I mean circumstances where if the statements were to be executed, it would imply that
something was very seriously wrong with the program or its environment. These are precisely the
circumstances to which assertions apply.
A simple assertion is a statement of the form:
assert logical _ expression;
Here, assert is a keyword and logical _ expression is any expression that results in a value of
true or false . When this statement executes, if logical _ expression evaluates to true , then the
program continues normally. If logical _ expression evaluates to false , the program will be
terminated with an error message starting with:
java.lang.AssertionError
This will be followed by more information about where the error occurred in the code. When this
occurs, the program is said to assert .
Search WWH ::




Custom Search