Java Reference
In-Depth Information
Chapter 10
Assertions
In this chapter, you will learn:
What an assertion is in Java
How to use assertions in Java programs
How to enable and disable assertions
How to check the status of an assertion
What Is an Assertion?
The literal meaning of assertion is to state something in a strong, confident, and forceful way. When you assert
“something,” you believe that “something” to be true. Note that asserting “something” does not make that
“something” always true. It simply means that chances are very high (or you are confident) that “something” is true.
Sometimes you may be wrong and that “something” may be false, even if you assert it to be true.
The meaning of an assertion in Java is similar to its literal meaning. It is a statement in a Java program. It lets
programmers assert a condition to be true at a specific point in the program. Consider the following snippet of code,
which has two statements with one comment in between:
int x = 10 + 15;
/* We assert that value of x is 25 at this point */
int z = x + 12;
The first statement uses two hard-coded integer values, 10 and 15 , and assigns their sum to the variable x . You
can assert that the value of variable x is 25 after the first statement is executed. Note the use of comments to make the
assertion in the above case. What is the probability that the value of x will be other than 25 in the above code? You may
think that the probability of x having a value other than 25 is zero. It means your assertion will be true all the time. So,
what was the point in adding a comment, which asserts that the value of x is 25 , when it is obvious by just looking at
the code? In programming, what seems obvious at one time may not be obvious at other times.
Consider the following snippet of code assuming that a getPrice() method exists:
int quantity = 15;
double unitPrice = getPrice();
/* We assert that unitPrice is greater than 0.0 at this point */
double totalPrice = quantity * unitPrice;
 
Search WWH ::




Custom Search