Assertions in Java Complete Tutorial

  • Post author:
  • Post category:Java

In this section, we will learn what the Assertion is and how to use them in Java.

What Does Assert Mean?

The literal meaning of Assert is to state something in a strong, confident, and forceful way. When we assert something, we believe that “something” is true.

But remember, when asserting something, that doesn’t mean “something” is always true! It just means that with a high percentage, that “something” is true! (But there’s a room for it to be false).

What is Assertion in Java?

The assertion in Java is similar to its literal meaning. It’s a statement in Java that either result true or false. It allows programmers to run a condition (assert a condition) at some point in a program.

The condition that we set for the assertion returns a boolean value. If the value was true, that means the assertion was right and so the program can continue to run its work.

But if the result of the condition was false (meaning assertion failed), thus it will cause the program to halt and an exception will throw that contains the details (the message and the place where the error occurred) to the output stream.

Assert Keyword in Java

In order to create an assertion in Java, we use the keyword `assert`.

This is how we use the assert keyword in Java:

assert condition;

assert condition: Message;

As you can see, this statement has two forms:

  • In the first form, we first start with the keyword `assert` and after that, comes an expression that should result in a boolean value. For example, we can use the comparison operators and compare the values of two variables to see if one is greater than the other, etc. The point is, the expression here must result in a boolean value.
  • The second form of using the `assert` keyword is to use a custom message as well. This custom message comes after the `condition` and we put a colon `:` between the condition and the message to separate them.

Now if the condition of the `assert` failed (meaning the result was false) then the `Message` will be sent to the output stream as part of the thrown exception.

This `message` typically is of type String but you can also use other expressions that result a value of any data type (except for Void) and Java is smart enough to convert the result of `message` expression to a String value and send that to the output stream.

Java Enable Assertions

By default, the `assertion` is not enabled in Java. This is because assertion is only useful when we are at development and test environment. So in order to prevent the penalty that may incur by using the assertions in the production environment, the designers of Java decided to disable the use of assertion by default.

So in order to enable assertion in Java, there are a couple of command-line options (or switches) that can enable assertions at runtime and at various levels.

For example, we have options to enable assertions in all user-defined classes, all system classes, all classes in a package and its sub-packages, just for one class, etc.

In the table below you can see how to enable Java Assertion:

Note: (each switch has a long and a short form)

Command-Line Switch

Description

-enableassertions, -ea

Used to enable assertions at runtime for system classes as well as user-defined classes. We can pass an argument to this switch to control the level at which assertions are enabled.

-enablesystemassertions, -esa

Used to enable assertions in all system classes. We cannot pass any arguments on this switch.

Enabling Assertion in the Intellij IDE:

To enable the assertion in the Intellij IDE:

  • Go to the Run menu and select the Edit-Configuration.
Intellij enable assertion
Intellij enable assertion
  • Now, in the VM options box of the opened window, enter the value `-ea`.
Intellij enable assertion VM options box
Intellij enable assertion VM options box

Now hit the OK button to apply the changes and close the window. After this, if you use the `assert` statement in a program, that will be checked at runtime.

Note: if you don’t enable the `assert` statement, depending on the IDE that you’re using, either an error will be thrown that points to the fact that you didn’t enable the assertion but used the assert statement in your program, or your ide will simply jump over any assertion statement in your program. (In case of the Intellij, the second method is used! Meaning, Intellij will simply ignore any use of the assert statement in a program, by default).

Java Assert Example:

int x = 10 + 15;

assert x == 25;

int z = x + 12;

Here, the condition of the assert statement is to see if the value of the `x` variable is equal to the value of 25. Now, because this value is actually equal to the value 25, thus the assertion is true and so the program can continue to run the rest of instructions of the program. (Note that if the assertion failed, the program would’ve ended right at the assertion statement and sent an exception to the output stream).

Java Disable Assertion

After testing your program, it’s best to disable the assertion in Java. That way, we will stop any potential penalty related to assertion that may incur at runtime.

In the table below you can see the list of command lines that can be used to disable the assertions in Java.

Command-Line Switch

Description

-disableassertions, -da

Used to disable assertions at runtime for system classes as well as user-defined classes. We can pass an argument to this switch to control the level at which assertions are disabled.

-disablesystemassertions, -dsa

Used to disable assertions in all system classes. We cannot pass any arguments on this switch.

Note: if you have the Intellij ide, simply go to the Edit-Configuration and remove the `-ea` switch from the `VM options` box.

When to use Assertion in Java?

Assertion is mainly used when we want to assert an assumption at a certain point in a program. Its main purpose is to be used for test and debugging but not in production!

So, use the assert statement when want to debug your program and make sure to remove it or disable the assertion after your test and debugging is done.

Java Lang AssertionError: (Java Assert Exception)

When an assertion failed (the result of the condition was false) Java will throw an error of type AssertionError into the output stream. So if you see this error on your program’s output, that means the target assert statement resulted false.

Example: throwing Assert Exception AssertionError

int i = 10 ;
assert i ==30: "Sorry the value of the i variable is not equal to 30 ";
System.out.println("You'll never see this message!");

Output:

Exception in thread "main" java.lang.AssertionError: Sorry the value of the i variable is not equal to 30

Reference Book:

“Beginning Java 9 Fundamentals, 2nd Edition” by Kishori Sharan

Leave a Reply