Monday, May 28, 2007 

Assertions in java

An assertion has a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state.Using assertions helps developers write code that is more correct, more readable, and easier to maintain.J2SE 1.3 and earlier versions have no built-in support for assertions. They can, however, be provided as an ad hoc solution.

import java.io.*;
public class AssertionExample {
public static void main(String argv[]) throws IOException {
System.out.print("Enter your marital status: ");
int c = System.in.read();
switch ((char) c) {
case 's':
case 'S': System.out.println("Single"); break;
case 'm':
case 'M': System.out.println("Married"); break;
case 'd':
case 'D': System.out.println("Divorced"); break;
default: assert !true : "Invalid Option"; break;
}
}
}

Make sure you use the -source option as follows:
prompt> javac -source 1.4 AssertionExample.java

If you now run the program using the command

prompt> java AssertionExample

and you enter a valid character, it will work fine. However, if you enter an invalid character, nothing will happen. This is because, by default,assertions are disabled at runtime. To enable assertions, use the switch -enableassertion (or -ea) as follows:

prompt> java -ea AssertionExample

About me

  • I'm phanindra
  • From Hyderabad, Andhra Pradesh, India
  • An Alumini of JNTU Hyd into happening IT industry...
My profile

Visitors
Bloggeries Blog Directory BlogRankings.com singapore blog directory blog search directory
Google
 
Web conceptoftheday.blospot.com