Assertion in Java

Posted by Somesh Shinde On Wednesday, 20 July 2016 0 comments

Assertion 

Assertion is a statement in java. It can be used to test your assumptions about the program.
While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose.

Syntax

There are two ways to use assertion. First way is:
  1. assert expression;  
and second way is:
  1. assert expression1 : expression2;  


Example

  1. import java.util.Scanner;  
  2.     
  3. class AssertionExample{  
  4.  public static void main( String args[] ){  
  5.   
  6.   Scanner scanner = new Scanner( System.in );  
  7.   System.out.print("Enter ur age ");  
  8.     
  9.   int value = scanner.nextInt();  
  10.   assert value>=18:" Not valid";  
  11.   
  12.   System.out.println("value is "+value);  
  13.  }   


If you use assertion, It will not run simply because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
Output: Enter ur age 11
        Exception in thread "main" java.lang.AssertionError: Not valid


Where to not use an Assertion

There are some situations where assertion should be avoid to use. They are:
  1. According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc.
  2. Do not use assertion, if you don't want any error in any situation.

0 comments:

Post a Comment