August 24, 2013

Assert Keyword and Its Use

The Dictionary Meaning of Assert is
1. To state or express positively;
2. To defend or maintain (one’s rights, for example).

Assert In JAVA :
Added to JAVA in version 1.4
Definition :
Java assertion feature allows developer to put assert statements in Java source code to help unit testing and debugging. Assert keyword validates certain expressions. It replaces the if block effectively and throws an AssertionError on failure and this can be enabled by passing –ea in VM arguments.
or can be stated as below.
Assert will throw a runtime error (AssertionError) if its condition is false. Asserts give you a streamlined way of documenting, checking, and enforcing correctness criteria for your code. The benefits are a language-level hook for defining and manipulating these correctness conditions. To the extent that you wish to enable or disable them (there are arguments about whether or not this is a good idea) you can do so from the JVM command-line

Assertions comes in two-flavors : really simple and simple.

Example (Really Simple)

public class AssertTest {

	public static void main(String[] args) {		
		String input = null;		
		assert (input != null);		
		System.out.println("Input Data :" +input);		

Example (Simple)

public class AssertTest {

	public static void main(String[] args) {		
		String input = null;		
		assert (input != null) : "Input Data is "+input;		
		//System.out.println("Input Data :" +input);		

The difference between the two is that the simple version adds a second expression, separated from the first(Boolean expression) by a colon, this expression’s string value is added to the stack trace. Both versions throw an immediate AssertionError, but the simple version gives you a little more debugging help.

Note : assert keyword can be used as a Keyword or as an identifier but not both. assert was added to Jdk 1.4.

How To Enable Assertions
if you run the code with VM argument as –ea (i.e. enable assertion) then it will throw AssertionError exception.

Output Will be something like below
Ex 1 :Really Simple
Exception in thread “main” java.lang.AssertionError
at in.bibek.AssertTest.main(
Ex 2 :Simple
Exception in thread “main” java.lang.AssertionError: Input Data is null
at in.bibek.AssertTest.main(

To set VM argument go to Run Configuration (right click on code area) to go Run as > Run Configurations > Arguments > VM Arguments (input field).

In Web apps you can enable assertion using VM arguments too (google for setting details).

Other Ref :

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.