Java Reference
In-Depth Information
additional benefit that programmers end up sharing coding techniques and learning
best practices in the process of reviewing each other's code. A related technique is called
pair programming
, in which two programmers work together at the same computer.
The programmers take turns, one typing while the other watches and looks for errors
and thinks about the task at hand.
pair
programming
Assertion Checks
An
assertion
is a sentence that says (asserts) something about the state of your program.
An assertion must be a sentence that is either true or false and should be true if there
are no mistakes in your program. You can place assertions in your code by making
them comments. For example, all the comments in the following code are assertions:
★
assertion
int
n = 0;
int
sum = 0;
//n == 0 and sum == 0
while
(n < 100)
{
n++;
sum = sum + n;
//sum == 1 + 2 + 3 + ... + n
}
//sum == 1 + 2 + 3 + ... + 100
Note that each of these assertions can be either true or false, depending on the
values of
n
and
sum
, and they all should be true if the program is performing correctly.
Java has a special statement to check whether an assertion is true. An assertion check
statement has the following form:
assert
assert
Boolean_Expression
;
If you run your program in the proper way, the assertion check behaves as follows:
If the
Boolean_Expression
evaluates to
true
, nothing happens, but if the
Boolean_
Expression
evaluates to
false
, the program ends and outputs an error message saying
that an assertion failed.
For example, the previously displayed code can be written as follows, with the first
comment replaced by an assertion check:
int
n = 0;
int
sum = 0;
assert
(n == 0) && (sum == 0);
while
(n < 100)
{
n++;
sum = sum + n;
//
sum == 1 + 2 + 3 + ... + n
}
//
sum == 1 + 2 + 3 + ... + 100