How to use assertions in Java

0
26


Writing programs that work correctly at runtime can be challenging. This is because our assumptions about how our code will behave when executed are often wrong. Using Java’s assertions feature is one way to verify that your programming logic is sound.

This tutorial introduces Java assertions. You’ll first learn what assertions are and how to specify and use them in your code. Next, you’ll discover how to use assertions to enforce preconditions and postconditions. Finally, you will compare assertions with exceptions, and find out why you need both in your code.

Download the source code for examples in this tutorial. Created by Jeff Friesen for JavaWorld.

What are Java assertions?

Before JDK 1.4, developers often used comments to document assumptions about program correctness. Comments are useless as a mechanism for testing and debugging assumptions, however. The compiler ignores comments, so there is no way to use them for bug detection. Developers also frequently do not update comments when changing code.  

In JDK 1.4, assertions were introduced as a new mechanism for testing and debugging assumptions about our code. In essence, assertions are compilable entities that execute at runtime, assuming you’ve enabled them for program testing. You can program assertions to notify you of bugs where the bugs occur, greatly reducing the amount of time you would otherwise spend debugging a failing program.

Assertions are used to codify the requirements that render a program correct or not by testing conditions (Boolean expressions) for true values, and notifying the developer when such conditions are false. Using assertions can greatly increase your confidence in the correctness of your code.

How to write an assertion in Java

Assertions are implemented via the assert statement and java.lang.AssertionError class. This statement begins with the keyword assert and continues with a Boolean expression. It is expressed syntactically as follows:

.

Copyright © 2020 IDG Communications, Inc.

LEAVE A REPLY