Java assert

The Java assert is a mechanism used primarily in nonproduction environments to test for extraordinary conditions that will never be encountered unless a bug exists somewhere in the code. When an extraordinary condition does occur, the Java assert triggers an AssertionError to be thrown, which will terminate a traditionally developed Java application.

Uniqueness of the Java assert statement

The term assert is a Java keyword that was introduced into the language with the JDK 1.4 release in February 2002. Java's assert keyword is unique in two very interesting ways:

  1. The intended use of this keyword is for test environments, or for temporarily performing debugging routines on production systems. No other keyword is targeted toward testing and debugging in the same way as the Java assert statement.
  2. The Java assert keyword is ignored when the Java Virtual Machine (JVM) is run using a default configuration. At startup, a special enableassertions runtime variable must be passed to the JVM as a command-line argument in order for code associated with with a Java assert to be executed. There is no other keyword in the Java language that is disabled by default at runtime. 

How assertions in Java work

The Java assert is intended to be a helpful tool for troubleshooting applications during the development and testing phase. The goal of assertions in Java is to test for conditions that should never actually occur. And if those conditions do occur, an error message is generated, and the application is terminated through the generation of an AssertionError.

What does the syntax of a Java assert look like?

The syntax of a Java assert is as follows:

assert : < boolean condition > : < string message to be logged >

A syntactically correct Java assert that would both trigger and log a string message to the Java console is as follows:

assert : (true == true) : “Something bad just happened.”;

The Java assert's boolean condition

The boolean condition of a Java assert statement can be as complicated as a program requires; however, the typical usage of an assertion's boolean condition is to simply check if a given variable is null, or if a numeric value falls outside of a given threshold.

Rules for the Java assert's string message

The Java assert's string message is most often just an informational piece of text, although any operation, method call or function that returns a value is valid. Any method call that has a void return type is forbidden, but any non-void return type is OK.

When to use a Java assert

When developing and testing applications, it's not unusual for software engineers to encounter problems that are difficult to replicate, making them problematic to troubleshoot. By using an assertion and testing a boolean condition, developers can place a trigger in their code that will fire off, provide an informational string message and terminate application flow when the fatal condition is encountered. The benefit of using the Java assert statement is it can help identify when problems occur and provide a stack trace indicating the sequence of events and method calls that led to the fatal condition occurring.

Using a Java assert example

Imagine an online shopping scenario where a shopping cart is created as soon as a user comes to the site, and that shopping cart is assigned a unique ID. And imagine in that same application, when the user checks out and purchases everything in their shopping cart, the unique ID must be retrieved. But let's say sometimes during the development and testing phase, when the user checks out, the ID associated with the shopping cart is null. The situation should never occur, and the problem is difficult to reproduce, which is making it difficult to troubleshoot. This would be a perfect scenario for using a Java assert statement.

In the code, anytime something is added to the shopping cart, or anytime the shopping cart is accessed programmatically, an assert statement could be included with a boolean condition that checks to see if the ID associated with the cart is null. The Java assert code with the boolean condition and a message string to log would look something like this:

Long id = shoppingCart.getUniqueId();

assert : (id != null) : “Why is the unique id of the cart null?”;

In theory, the boolean condition of a Java assert statement should never be true. However, if the boolean condition is true, the assert is triggered, the application is terminated and the string message is written to the console, helping the developer understand the conditions that are causing what should be an impossible application state.

Why to use a Java assert statement

Prior to the introduction of the Java assert, software developers would write conditional statements in their code to check for erroneous conditions. The Java assert example given above could easily be replicated using an if statement and Java's exception-handling tools.

Long id = shoppingCart.getUniqueId();

if (id == null) {

  throw new Exception(“Why is the unique id of the cart null?”);


Any developer who has worked tirelessly to troubleshoot a persnickety software bug has no doubt littered their code base with similarly structured code. To troubleshoot a problem, or even to verify that code is working properly, these types of conditional statements regularly make their way into the code.

Assertions in Java vs. a conditional statement

The problem with using a conditional statement is once a problem is solved, rarely do developers go back and remove each and every one of these test cases. As a result, these conditional statements make their way into production and clock cycles are wasted, as conditions that were only true when a bug existed in code are needlessly checked.

Contrast that with assertions in Java. Since the default behavior of the JVM is to ignore a Java assert at runtime, all assert statements that may still linger within the code base, statements whose sole purpose is troubleshooting, are ignored, and clock cycles are not wasted on them. So, there is a performance benefit to using the Java assert instead of having developers write conditional statements.

Debugging production with Java assert statements

So, when developers use conditional statements in their code for troubleshooting purposes, they are supposed to remove those statements when a given bug is fixed. They don't always, but they're supposed to do so. But let's imagine they do remove all of the conditional statements that check for the erroneous condition the bug creates, only to have the bug rear its ugly head again. Now, the developer has to go back into the code and add all of those conditional statements back in again. Furthermore, that process would first have to be done in the development environment, moved to a test and quality-assurance environment, and then promoted to production.

Code changes in enterprise systems need to go through a rigorous set of checks and balances before going live. Decorating code with if statements that log the state of a misbehaving application and then moving that code into production can be a time-consuming process.

Now, compare a program that uses conditional statements to troubleshoot problems and contrast it against a program that uses the Java assert statement. Since a Java assert is ignored by default at runtime, there is no need to remove Java assert statements from code. So, all of the Java assert statements used during development would still be there in production. They would be dormant, but they would still be there.

To activate them, all the DevOps team has to do is restart the JVM with the enableassertions JVM runtime variable added. When that happens, all Java assert statements are activated, and any string messages associated with a triggered Java assert will be written to the log files.

Benefits of using a Java assert

The other key benefit to using a Java assert statement is the fact the syntax is concise, and it is easily recognized by other developers who may be reading or maintaining the code. With an if statement, it might take some time to recognize that it's being used for debugging purposes, as opposed to implementing a business requirement. There is never any confusion to the purpose of a Java assert.

When not to use assertions in Java

Assertions should be used to test for situations, conditions and application flows that should simply not be possible. Situations that do not fall into these scenarios should be handled using other error- or exception-handling mechanisms.

For example, problems that deal with the environment should not best tested for using an assert. So, checking to see if the database is running or if a website URL exists are not proper uses of the Java assert statement.

Fundamental problems with the JVM are also not appropriate uses of a Java assert. So, checking to see if the JVM is out of memory, if there is a buffer overflow happening or if a user has appropriate access rights to interact with a secure resource are not situations when you use a Java assert statement.

Validation of user input is also not an appropriate use of an assert in Java. Checking to see if a certain escape character has made it into a database query string after validation code has run that makes sure SQL injection attacks do not occur might be valid, because it is testing a situation that should never happen. But validation of user input itself is not a good example of when to use a Java assert statement.

Why Java asserts are disabled by default

When a Java assert's condition is true, an AssertionError is generated and thrown according to the Java language's exception-handing semantics. It should be noted that the AssertionError is a subclass of java.lang.Error, and not java.lang.Exception. As a result, the AssertionError will bypass most typical exception-handling routines, as they only handle subtypes of Exception and RuntimeException, not subclasses of Error. The result is the AssertionError will cause a running application to terminate.

This behavior is intended, as the language designers wanted the generation of an AssertionError to be a serious condition that requires a developer's immediate attention. However, it is also the reason why Java asserts are disabled by default. The ability for a single line of code to terminate the execution of a running JVM is not a behavior that you want to have enabled in production runtime.

The Java assert and backward compatibility

Although the assert keyword was introduced in Java 1.4, code written prior to the February 2002 release was still backward-compatible. The exception to that rule was any code that actually used the word assert as a variable name. Since Java does not allow keyword to be used as variable names, any code written prior to the 1.4 release that used the keyword assert as a variable would have to change the variable name in the Java source to something different and recompile the code.

This was last updated in September 2017

Continue Reading About Java assert

Dig Deeper on Java Development Tools



Find more PRO+ content and other member only offers, here.

Join the conversation


Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

Why do you think we don't see assertions in Java code more often?
Still learning java on my own. Thanks for the tips.


File Extensions and File Formats

Powered by: