Sunday, January 25, 2009

Simple Java Program that uses my assertion

/*
------------------------------------------------------------------------
Simple Java Program that uses my assertion
------------------------------------------------------------------------
*/

class MyAssertionExample{

static boolean myassertionenabled;//default value is false
static void myassert (boolean b){
if(myassertionenabled & !b){
throw new AssertionError();
}

}

public static void main(String args[]){

try{
if (args[0].equals("ea")){
myassertionenabled=true;}
}catch(ArrayIndexOutOfBoundsException AE){}//dont throw exception if no arguments are passed
int a=1;
try{
myassert(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 MyAssertionExample.java

C:\Users\flower\Documents\javaprogs>java MyAssertionExample ea
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 MyAssertionExample

*/

No comments: