Assertions

In this lesson, we will explore another way to find logical errors in a program.

What is an assertion?

An assertion is a statement of truth about some aspect of our program’s logic. You can think of it as a Boolean expression that is true, or that at least should be true, at a certain point. If an assertion is false, something is wrong with our program. We can state assertions as comments within our code. For example, if at some point in a method’s definition we know that the variable sum should be positive, we could write the following comment:

// Assertion: sum > 0

Such comments point out aspects of the logic that might not be clear. Additionally, they provide places for us to check the accuracy of our code during debugging.

The assert statement

Java enables us to do more than simply write a comment to make an assertion. We can use an assert statement, such as:

assert sum > 0;

to enforce the assertion. If the Boolean expression that follows the reserved word assert is true, the statement does nothing. If it is false, an assertion error occurs and program execution terminates.

However, Java ignores assert statements at execution time by default unless we give a command to enable them. Each time we run the program, the assertions will be ignored, unless we once again use a command to enable them. Thus, we can leave the assert statements in place after we have finished debugging our program, without wasting execution time.

📝 Note: Enabling assertions

Although you will not be able to enable assert statements during this course, we will enable them for you from time to time. The Appendix will show you how to enable them after you finish the course.

Example

The following simple program will show you what happens when an assertion error occurs. When you click the RUN button, assertions will be enabled.

Get hands-on with 1200+ tech skills courses.