Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
This article introduces you to Assertions In Java a simple yet important concept and follow it up with a programmatic demonstration. Following pointers will be covered in this article,
So let us get started,
Want to test if an assumption is right in your program? Well, you can do so with assertion statements in Java. You can use the assert keyword to create assertions that let you test your assumptions in a program.
Let’s take an instance. An employee in a company ABC cannot have an age that is a negative number. You can use an assertion for this to ensure that an employee’s age is not a negative number.
Let’s take another instance. If your method calculates the speed of a particle, then your assumption is that the speed of the particle is less than the speed of light. So, to test this assumption, you can use assertion statements in Java.
The Syntax
There are two forms of the assertion statement:
assertexpression1;
Here,
expression 1 is a boolean expression.
assert expression1 : expression2 ;
In this form, expression 1 is a boolean expression, and expression 2 has a value that will be compared to expression1.
Now, you might ask – which form do you choose for your programs? You can use the second form when your program has additional information that might help diagnose the errors or failures in the program.
Prior to java 1.4, you could have used the keyword “assert” to name your variables, methods, functions and much more. With newer versions of the JVM, this can potentially cause a naming clash – so you need to be a little mindful about this fact.
Moving on with this article on Assertions in Java
You might think that an assertion statement in Java might be unnecessary. You might find it unnecessary for small programs. But, when it comes to big programs with complex logic, these assertion statements come in handy.
The primary use of assertion statements is for debugging and testing. If there is any failure in the assertion statement, then the JVM will throw an error that is labelled as an AssertionError. As you can see, this offers an effective way of detecting and correcting errors in a program.
In addition to debugging and testing, the assertion statement makes your code more readable. Let’s take an instance:
The below code will help us verify certain conditions that can prevent the application from working properly.
Connection conn = getConnection(); if(conn == null) { throw new RuntimeException("Connection is null"); }
With a single assertion statement, you can essentially do away with the “if and throw” statement as shown below:
Connection conn = getConnection(); assert conn != null;
Moving on with this article on Assertions in Java
As Java assertions use the assert keyword, you won’t need to import packages or libraries. As mentioned earlier, you can use the assert keyword for variables, methods and functions. For backward compatibility, and in order to avoid a potential naming clash, the JVM disables assertion validation by default. The assertions must be enabled explicitly. You can do so with a command line argument (-enableassertions), or by using its shorthand (-ea).
Let’s consider a few examples:
java -ea com.baeldung.assertion.Assertion
The above enables assertion for classes.
java -ea:com.baeldung.assertion… com.baeldung.assertion.Assertion
You can enable assertions for particular packages and classes as well. This is shown in the above example where we have enabled assertions for the classes in the com.baeldung.assertion package.
Now that we have learnt about enabling assertions, let’s see how we can disable them. Much like enabling assertions, disabling can be done using a command line argument (-disableassertions) or its shorthand (-da) for specific packages and classes.
Moving on with this article on Assertions in Java
How to Use Java Assertions?
There are two things that you need to implement assertions in your program – the assert keyword and a boolean condition. Let’s take an example with a code snippet:
public void setup() { Connection conn = getConnection(); assert conn != null; }
You can also use a string for the above assertions as shown below:
public void setup() { Connection conn = getConnection(); assert conn != null : "Connection is null"; }
In the above code snippet, if there is an AssertionError, the string will be used to construct the error.
In both of the above cases, the code checks if the connection to an external source returns a non-null value. If the value is null, then the JVM will throw an AssertionError automatically.
In the second example, the string that we have used shows up in the stack trace when there is an AssertionError. This additional information will be useful when you are attempting to debug the program. These detailed messages will help you fix an error that would have caused the assertion to fail. So, when you run the class with assertions enabled, the result will be similar to the one below:
Exception in thread “main” java.lang.AssertionError: Connection is null
at com.baeldung.assertion.Assertion.setup(Assertion.java:15)
at com.baeldung.assertion.Assertion.main(Assertion.java:10)
Let’s consider a simple example:
import java.util.Scanner; class AssertionExample { public static void main( String args[] ) { Scanner scanner = new Scanner( System.in ); System.out.print("Enter your age "); int value = scanner.nextInt(); assert value>=18:"Not valid"; System.out.println("value is "+value); } }
Now that you have the code in hand, it is time to run it. Since, assertions are disabled by default, you will have to enable them.
You can compile the above code with the following: javac AssertionExample.java
You can then run it using the following: java -ea AssertionExample
The output for the above code is:
Enter your age 11
Exception in thread “main” java.lang.AssertionError: Not valid
As you can see, we have given 11 as a value for age. The program does not treat it as a legitimate value. So, you will see an AssertionError.
Moving on with this article on Assertions in Java
While it is good to have assertions in situations that include internal invariants, control-flow invariants, preconditions, postconditions and class invariants, there are some situations where assertions should not be used.
Let’s explore more on these:
For Argument Checking in Public Methods
You should understand that argument checking is a part of published specifications or contracts of a method. These must be followed irrespective of whether assertions are enabled or not.
Moving on with this article on Assertions in Java
Using Assertions for Operations
By default, assertions are disabled. Your program should not assume that the boolean expression in an assertion statement will always be evaluated.
Let’s take an example as to how this might affect your program. Say, you want to remove all the null elements from a list of names, and you are aware that your list contains null elements.
assert names.remove(null);
The above code snippet would work if assertions were enabled. But, it would fail if assertions were disabled as the code will not remove any null elements. To fix this problem, you could employ the below code snippet in your program:
boolean nullsRemoved = names.remove(null);
assert nullsRemoved;
The above code snippet will remove null values, even if assertions were disabled.
Now after executing the above Java program you would have understood “Assertions in Java”. Thus we have come to an end of this article on ‘Quicksort in Java’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co