How to use assertions in Java

Use Java assertions to document program correctness and more quickly test and debug your programs

How to use assertions in Java
Getty Images

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.downloadGet the codeDownload 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.  

[ Also on InfoWorld: JDK 15: The new features in Java 15 ]

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.00:00 of 11:14Volume 0% 

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:

assert BooleanExpr;

If BooleanExpr evaluates to true, nothing happens and execution continues. If the expression evaluates to false, however, AssertionError is instantiated and thrown, as demonstrated in Listing 1

SevenMentor Pvt Ltd Java AngularJS MeanStack Classes

\

Address: Dnyaneshwar Paduka, Chowk, Shreenath Plaza, Office No 42 A-wing, Second Floor, Pune, Maharashtra 411005

HoursOpen ⋅ Closes 7PMUpdated by business 7 days ago

Phone: 08237077325

Appointments: sevenmentor.com

https://www.sevenmentor.com/java-training-classes-in-pune.php

Suggest an edit · Own this business?

Comments