The good thing about Assertion in Java is that you can enable or disable Assertion at runtime. The designer of java are really very thoughtful, they have thought of many situations while designing java and its API. one of the gems is the ability to enable or disable assertion in runtime without any change on code. In last article we see how Assertion works in Java and now we will see some step by step guide on how to disable or enable Assertion in Java By default assertions in Java are disabled at runtime and JVM provides following options to deal with assertion in Java :
Enable or disable Assertion in Java
--ea[:...|:] or enableassertions (to enable assertion at a particular package and class level)
--da[:...|:] or disableassertions (to disable assertion on a package or class level)
--esa or enablesystemassertions (for enabling system assertion)
--dsa or disablesystemassertions (for disabling system assertion)
1) if we use -enableassertions or -disableassertions without arguments it enables or disable assertion in all classes except System classes
2) if we use -ea or -da with "packageName..." it enables or disable assertions in the named package and any sub package.
3) -enableassersions with "..." only enable assertions in the unnamed package in current working directory.
4) -enableassertions with "classname" only enable assertion in the named class in Java.
Example of Enable and Disable Assertion in Java
Here is an example of enabling assertion in java: in below example assertions will be enabled for package "com.onlinestockbroker.electronicTrading" and it sub package.
That’s all on how to enable and disable Java Assertion. Important point is that you don’t need to change anything on code and can disable assertion at runtime with just changing some JVM options, which gives you the flexibility to run the same code on development and production environment. While in development you can enable assertion, you can disable assertion in production with just JVM switch.