Monday 22 July 2013

What is Assertion in Java?




According to Sun, we can use assertion to test our assumption about programs. That means it validates our program!
In another words we can say that assertions ensures the program validity by catching exceptions and logical errors. They can be stated as comments to guide the programmer. Assertions are of two types:

1.       Preconditions: Preconditions are the assertions which invokes when a method is invoked.
2.       Postconditions:  Postconditions are the assertions which invokes after a method finishes. 
Where to use Assertions?
We can use assertions in java to make it more understanding and user friendly, because assertions can be used while defining preconditions and post conditions of the program.

Example of AssertionExample.java

import java.util.Scanner;

public class AssertionExample
  {
 public static void main( String args[] )
  {
  Scanner scanner = new Scanner( System.in );

  System.out.print( "Enter a number between 0 and 20: " );
  int value = scanner.nextInt();
  assert( value >= 0 && value <= 20 ):
  "Invalid number: " + value;
  System.out.printf( "You have entered %d\n", value );
 }
  }

 Before running above example enable  the assertion at your environment with following command.
java -ea AssertionExample

No comments:

Post a Comment