In this tutorial, we will learn about what is the assertion in Java. Java assertions are a powerful tool that developers can use to test assumptions in their code.
When a programmer executes a Java assertion, they assume the statement’s truthfulness. If it fails, the Java Virtual Machine (JVM) throws an AssertionError during runtime. This feature had utilized for testing code since its introduction in Java version 1.4.
Assertions are particularly helpful for examining logical situations in a program where uncertainty may arise, unlike regular exceptions that can cover a broad range of errors.
Developers can use assertions carefully in private methods or conditional cases where they have maximum control. They can also be used at the beginning of any method to verify that the necessary preconditions are met before the code runs. However, it’s vital to use assertions judiciously. They don’t employ to replace error messages or used public methods to verify arguments.
However, it’s crucial to use them with care and in combination with other error-checking mechanisms to ensure the code’s robustness and dependability.
So now we have to know how it works and for that, we have first to know what is an assert in java.
Use of assert keyword in Java
Java language offers developers the powerful tool of the “assert” keyword to verify the assumptions they have made about their program or its state. This keyword enables programmers to provide assertions that check for specific conditions that could potentially disrupt the smooth functioning of their program.
The “assert” keyword has been available in Java since version 1.4, yet remains a relatively unknown feature. To utilize the “assert” keyword, programmers must incorporate it into an Assert statement. By doing so, they can ensure that their program is operating as expected. To catch any potential issues before they cause significant problems.
Overall, the “assert” keyword is an invaluable tool for Java developers. It improves the reliability and robustness of their programs. By utilizing this feature, they can gain greater confidence in their code and ensure that it is functioning optimally.
Example :
public void setup_connetion () {
Connection conn = getConnection ();
assert conn != null;
}
Now by default assertions are disable, to use them we have to enable them.
Enabling Assertions
General Syntax for that –
java βenableassertions: arguments
or
java βea: arguments
There are several ways to enable assertions in Java:-
- java βea
When the above command is given in the command line, then the assertions are enabled in all classes except for system classes.
- java βea Main
The above command enables assertion for all classes in the Main program.
- java βea TestClass Main
This command enables assertions for only one class β βTestClassβ in the Main program.
- java βea com.packageNameβ¦ Main
The above command enables assertion for package com.packageName and its sub-packages in the Main program.
- java βea β¦ Main
Enables assertion for the unnamed package in the current working directory.
- java βesa: arguments OR java βenablesystemassertions: arguments
The above command enables assertions for the system classes.
Disable Assertion
Assertions can also be disable in the same way they are enabled but with a little modification
java βdisableassertions: arguments
or
java βda: arguments
Different Examples of assertion in Java:
public class Main {
public static void main(String args[]) {
String[] weekends = {"Friday", "Saturday", "Sunday"};
assert weekends.length == 2;
System.out.println("There are " + weekends.length + " weekends in a week");
}
}
Output :
There are 3 weekends in a week
We get this output as now assertions are disabled by default but when we enable assertion we get the following output
Exception in thread "main" java.lang.AssertionError
Example 2: assertion with the expression
public class Main {
public static void main(String args[]) {
String[] weekends = {"Friday", "Saturday", "Sunday"};
assert weekends.length==2 : "There are only 2 weekends in a week";
System.out.println("There are " + weekends.length + " weekends in a week");
}
}
Output :
Exception in thread "main" java.lang.AssertionError: There are only 2 weekends in a week
From the example provided earlier, we can observe that the expression used is handed over as an argument to the AssertionError object constructor. When we enable assertions and if our assumption turns out to be false, then an exception is thrown along with a relevant message.
Such messages serve a crucial role in identifying and resolving the cause of the assertion failure. By providing specific details about the error, these messages aid in debugging and correcting the problem at hand. It is, therefore, essential to include clear and informative messages when using assertions, as they can significantly improve the efficiency of the debugging process.
Now the last one i.e. what is an assertion error in Java?
Assertion error in Java
- The java.lang.AssertionError class is a subclass of java.lang.Error.
- Thus AssertionErrors is unchecked. They can be explicitly caught and handled using the try-catch construct, and the execution continues normally, as one would expect.
- However, errors are seldom caught and handled by the programs, and the same applies to AssertionErrors. Catching these errors would defeat the whole purpose of the assertion facility
Follow for More Info β https://instagram.com/developerhelps?igshid=MzRlODBiNWFlZA==