This Java Assert Tutorial Explains all about Assertions in Java. You will learn to Enable & Disable Assertions, how to use Assertions, Assert Examples, etc:
In our earlier tutorials, we have already discussed exceptions in Java. These are the errors that are caught at runtime. Similar to exceptions there are some other constructs that we can use at compile time to test the correctness of code. These constructs are called “Assertions”.
In this tutorial, we will discuss Assertions in Java in detail. We can define an Assertion as a construct that allows us to test the correctness or clarity of assumptions that we have made in our Java program.
=> Take A Look At The Java Beginners Guide Here.
Table of Contents:
Assertions In Java
Thus when we are executing assertion in a program, it is assumed to be true. If it becomes false or fails then JVM will throw an AssertionError.
We use assertions during development for testing purposes. At runtime, assertions are disabled by Java.
How do assertions differ from normal exceptions?
Unlike normal exceptions, Assertions are mainly useful to check the logical situations in a program about which we have doubts. Also contrary to normal exceptions that also can be thrown at run-time, assertions are disabled at run-time.
Assertions can be used in the places in the code where the developer has maximum control like they can be used as parameters to private methods. Assertions can also be used with conditional cases. Similarly, conditions at the start of any method can contain assertions.
However, assertions should not be taken as a replacement for error messages. Neither the assertions should be used in public methods, for example, to check arguments. Most importantly we should not use assertions on command-line arguments in Java.
In Java, assertions are disabled by default. So for assertions to work in a Java program, we have to first enable the assertions.
Enable Assertions In Java
To enable assertions, we have to do it from the command line.
Following is the general syntax for enabling Assertion in Java.
java –ea: arguments
or
java –enableassertions: arguments
As an example, we can enable assertions for a particular class as shown below:
java –ea TestProgram
or
java –enableassertions TestProgram
Here, TestProgram is a class for which the assertion is to be enabled.
When the condition is true in the assert statement in the program and assertions are enabled, then the program will execute normally. When the condition is false and assertions are enabled, then the program throws AssertionError and the program stops.
There are various variations for enabling assertions using the command line.
#1) java –ea
When the above command is given in the command line, then the assertions are enabled in all classes except for system classes.
#2) java –ea Main
The above command enables assertion for all classes in the Main program.
#3) java –ea TestClass Main
This command enables assertions for only one class – ‘TestClass’ in the Main program.
#4) java –ea com.packageName… Main
The above command enables assertion for package com.packageName and its sub-packages in the Main program.
#5) java –ea … Main
Enables assertion for the unnamed package in the current working directory.
#6) java –esa: arguments OR java –enablesystemassertions: arguments
The above command enables assertions for the system classes.
Disabling Assertions
We can also disable assertions through the command line.
The general syntax to disable assertions in Java is:
java –da arguments
OR
java –disableassertions arguments
Similarly to disable assertions in System classes, we use the following syntax:
java – dsa: arguments
OR
java –disablesystemassertions:arguments
“assert” Keyword In Java
Java language provides the keyword “assert” that allows developers to verify the assumptions they have made for the program or state of the program.
So we can use the “assert” keyword to provide assertions in Java to verify conditions that might otherwise prevent the program from working smoothly.
The keyword “assert” is used from Java 1.4 but remains the little known keyword in Java. When we use the assert keyword in Java, we have to do so in an Assert statement.
Assert Statement In Java
In Java, the assert statement starts with the keyword ‘asset’ followed by a Boolean expression.
The assert statement in Java can be written in two ways:
- assert expression;
- assert expression1: expression2;
In both the approaches, the expressions used with the Assert keyword are the Boolean expressions.
Consider the following statement as an example.
assert value >= 10 : “greater than 10”;
Here, the assert statement checks for a condition and if the condition is true, a message is printed. Thus we can also have assertions with our message.
How To Use Assert In Java
So far, we have discussed the assert keyword and assert statement in Java. Now, let us consider an example to demonstrate how to use assert in Java.
To add assertions, we have to simply add an assert statement as follows:
public void setup_connetion () { Connection conn = getConnection (); assert conn != null; }
We can also give the above assert differently as shown below:
public void setup_connection () { Connection conn = getConnection (); assert conn != null: “Connection is null”; }
Both the above code constructs check if the connection returns a non-null value. If it returns a null value, then JVM will throw an error – AssertionError. But in the second case, a message is provided in the assert statement so this message will be used to construct AssertionError.
In the second case with assertions enabled, the exception will look like:
Exception in thread "main" java.lang.AssertionError: Connection is null at line numbers…
Assert Example In Java
Let’s implement an example of using Assertions in Java.
public class Main { public static void main(String[] args) { try { System.out.println("Testing Assertions..."); assert true : "We don't see this."; assert false : "Visible if assertions are ON."; } catch (AssertionError e) { e.printStackTrace(); } } }
Output
The above output is given when the assertions are not enabled. If the assertion was enabled, then the second message (assert false) will be displayed.
Now let’s demonstrate another example. Note that here we have enabled the assertion in Java on our machine where we are running this program.
class Main { public static void main(String args[]) { String[] weekends = {"Friday", "Saturday", "Sunday"}; assert weekends.length == 2; System.out.println("We have " + weekends.length + " weekend days in a week"); } }
Output
As the weekend length doesn’t match the length specified in the assert statement, the above exception is thrown. If the assertion was disabled, then the program would have displayed the message specified instead of assert exception.
Why Are Assertions Used In Java?
We use assertions in our Java program to make sure that the assumptions we have made in our program are correct.
For example, if we want to make sure that the code that seems to be unreachable is indeed unreachable. Or we want to make sure that any variable has a value in a specified range.
When we make such an assumption, we provide assertions to make sure that they are indeed correct.
Frequently Asked Questions
Q #1) Does assert throw an exception Java?
Answer: Assert usually throws “AssertionError” when the assumption made is wrong. AssertionError extends from Error class (that ultimately extends from Throwable).
Q #2) What happens when an assert fails in Java?
Answer: If assertions are enabled for the program in which the assertion fails, then it will throw AssertionError.
Q #3) What does an assert return in Java?
Answer: An assert statement declares a Boolean condition that is expected to occur in a program. If this Boolean condition evaluates to false, then an AssertionError is given at runtime provided the assertion is enabled.
If the assumption is correct, then the Boolean condition will return true.
Q #4) Can we catch the assertion error?
Answer: The AssertionError thrown by the assert statement is an unchecked exception that extends the Error class. Thus assertions are not required to declare them explicitly and also there is no need to try or catch them.
Q #5) How do you assert an exception?
Answer: To assert an exception we declare an object of ExpectedException as follows:
public ExpectedException exception = ExpectedException. none ();
Then we use it’s expected () and expect message () methods in the Test method, to assert the exception, and give the exception message.
Conclusion
With this, we have concluded this tutorial on assertions in Java. We have discussed the definition and purpose of assertions in Java. To use assertion in Java program we have to first enable them to use the command line.
We explored the various ways using which we can enable assertions at the program level, package level, directory level, etc. Assert keyword and assert statements in Java and their detailed syntax with programming examples was discussed. The assert keyword and asset statements help us to use assertions.
We saw that an AssertionError is given when an assertion fails. Assertions in Java are mostly used at compile time and they are by default disabled at runtime.
Furthermore, assertions are mostly used in the JUnit framework of Java in which we write the test cases to test applications.
=> Read Through The Easy Java Training Series.