Simple Intro to Java’s assert Keyword

Good day, guys! Today we’ll look at the assert keyword in Java and when it’s appropriate to use it.

Intro

In Java 1.4, the assert keyword was introduced. In Java, there are two ways to use the assert keyword.

1. assert Expression1;

Here, Expression1 is a boolean that will be evaluated. If the assertion evaluates to be false, an AssertionError will be thrown.

2. assert Expression1 : Expression2;

Here, Expression1 is a boolean that will be evaluated. If the assertion evaluates to be false, an AssertionError will be thrown.

Here Expression2 is a String that we will be thrown with the AssertionError.

Usage

When we run the java file in the regular way, the assertions will be disregarded. To have the compiler consider the assertions, we must manually activate assertions with -ea.

When to Use?

You can use an assertion when dealing with scenarios when you know something is definitely true. This article from the Java Docs provides a simple introduction will the all the usages.

When not to Use?

Do not use assertions inside public methods. You are supposed to use try-catch blocks and handle exceptions in public methods.

Do not use assertions as a safety mechanism. Your code is supposed to be working properly without assertions. You should only be using assertions to improve your developer experience (for sanity checks, basically).

Further Reading

If you want to learn more regarding assertions, I’d recommend you to read the following article from Java Docs.

Published by Thisura Thenuka

I am a passionate software engineering student. But cricket is my first love ❤

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: