Java Reference
In-Depth Information
might have to run this application a few times to see the assertion error, but first you
need to learn how to enable assertions, which I discuss later in this chapter.)
Caution Be careful when using an assertion statement to detect code that should
ever be executed. If the assertion statement cannot be reached according to the rules
set forth in The Java Language Specification, Third Edition, by James Gosling, Bill
available at (
html/j3TOC.html ) , the compiler will report an error. For example, for(;;);
assert false; causesthecompilertoreportanerrorbecausetheinfiniteforloop
prevents the assertion statement from executing.
Design-by-Contract (see
Design_by_contract ) is a way to design software based on preconditions, post-
conditions,andinvariants(internal,control-flow,andclass).Assertionstatements sup-
port an informal design-by-contract style of development.
A precondition issomethingthatmustbetruewhenamethodiscalled.Assertionstate-
guments are legal. Listing 3-36 provides an example.
Listing 3-36. Verifying a precondition
class Lotto649
public static void main(String[] args)
// Lotto 649 requires that six unique umbers be
int[] selectedNumbers = new int[6];
// Assign a unique random umber from 1 to 49 (inclus-
ive) to each slot
// in the selectedNumbers array.
for (int slot = 0; slot < selectedNumbers.length;
Search WWH ::

Custom Search