Using Assertions in Java
I’ve been working on a project this week and have been delighted to see that the original team of programmers who developed it have made the effort to use assertions in their code.
The assert keyword was introduced in Java 1.4 and has since been a sadly under-used language feature. Assertions offer developers a neat way to implement error detecting statements that are only active during development and can be turned off in production environments.
For example you might want to check that appropriate values are passed to a method during development to ensure that it is being called correctly:
private void onlyPositiveNumbersPlease(int i) {
assert i > 0;
//rest of method implementation...
}
If the assertion fails, then an AssertionError is thrown. If you have a lot of assertions in your code, then its useful to be able to specify a value that will be used in the error message:
private void onlyPositiveNumbersPlease(int i) {
assert i > 0 : "only positive numbers are allowed";
//rest of method implementation...
}
The value that is specified can also be any primitive type, for example:
File f = loadFile(); assert f != null : 404;
In all cases, the value is converted to a String and set as the detail message of the AssertionException.
When the Java source is compiled, assertions instructions are included in the bytecode that is generated. However, by default, the assertions are not executed at runtime.
In order to activate all of the assertions, a command line flag must be passed to the JVM:
$ java -ea co.uk.smartkey.ui.MainClass
it is also possible to specify that assertions should only be activated for classes within a certain package. For example to run the same application as before, but only activate assertions for classes in the util package of our application, you could use something like:
$ java -ea:co.uk.smartkey.util co.uk.smartkey.ui.MainClass
if you just wanted to turn on assertions for a single class, you can specify the class name instead of the package name. Finally, if you really feel the need to, you can turn on assertions in the Java system classes with this:
$ java -esa co.uk.smartkey.ui.MainClass
Personally, I like using assertions as they can help to iron out problems during development that are unlikely to need checking for in production. Language level support for them means that the statements are only used if the JVM is launched with them activated; this ensures that there is no performance overhead associated with them when they are not in use.

March 9, 2010 - 3:04 pm
Using Java assertions to test the params of a public method is bad. Do not use assertions to check the parameters of a public method.
read (Preconditions)
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html