Sunday, January 25, 2009

Simple Java Program to understand assertions

/*
------------------------------------------------------------------------
Simple Java Program to understand assertions
------------------------------------------------------------------------
*/

class AssertionExample{

public static void main(String args[]){

int a=1;
try{
assert(a==2);//value of 'a' should be 2, else throw an assertion exception error
}catch(AssertionError E){
System.out.println("Value of a is not equal to 2 and assertion is enabled");
}
}
}
/*
------------------------------------------------------------------------
Output of AssertionExample with assertions enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac AssertionExample.java

C:\Users\flower\Documents\javaprogs>java -ea AssertionExample
Value of a is not equal to 2 and assertion is enabled

------------------------------------------------------------------------
Output of AssertionExample with assertions not enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java AssertionExample

*/

No comments: