Assertion in Java

Assertion in Java

Ads

Tutorials   

Assertion in java

To check or test your assumption in your code or program, assertion is used . For example , if you write a method for calculating the speed of a car , you can assert that calculated speed must be less than 100km/hr.

Given below the two forms of the assertion. The simple first form is :

assert BooleanExpression ;

In the above statement, system executes assertion statement and evaluate boolean expression and if it false, it throws exception AssertionError.

The second form of the assertion is :

assert BooleanExpression : Expression2 ;

Here Expression2 is an expression who has value or returns value, it can't be a void method.

Compiling Code containing assertions

Compiler accept your code having assertions, if you compile it as follows :

  javac ?source 1.4 DemoAssert.java     

The javac compiler accept your program, if you compile your .java file with -source 1.4 command-line option.

Enable/disable assertion at runtime

By default assertions are disabled at runtime. You can enable assertion at runtime as follows :

   java -ea DemoAssert             

OR

   java ?enableassertion DemoAssert     

 

You can disable assertion at runtime as follows :

   java -da DemoAssert             

OR

   java -disableassertions DemoAssert     

EXAMPLE

Given below a sample example to check the value must lie in between 0 & 20 :

import java.util.*;
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 );
} 
}

Output

If you enter value in between 0 & 20, output should be :

C:\>java -ea AssertionExample
Enter a number between 0 and 20 : 4
You have entered 4

If you enter value greater than 20, For example 21, the following message will be displayed :

C:\>java -ea AssertionExample
Enter a number between 0 and 20 : 21
Exception in thread "main" java.lang.AssertionError: Invalid number: 21
at AssertionExample.main(AssertionExample.java:15)

Advertisements

Share on Google+Share on Google+

Assertion in Java

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Assertion in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads