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.