Presents your JAVA E-NEWSLETTER for April 24, 2003 <-------------------------------------------> ASSESS THE BENEFITS OF ASSERTIONS IN YOUR CODE Assertions have been part of other programming languages for a long time, but they've only recently reached the Java language with the release of 1.4. The cost of using assertions is small, especially when compared to the improvements assertions will make in your code. An assertion is a statement by the developer that a certain expression must be true or else the application should stop immediately. You can disable assertions in production to improve application performance--a benefit allowed in all assertions, including the Java implementation. http://java.sun.com/j2se/1.4.1/docs/guide/lang/assert.html There are two ways to code assertions. The first way simply takes a Boolean expression. If the expression resolves to true, the assertion is ignored. If it resolves to false, a new java.lang.AssertionError is thrown: ... assert (arg != null); ... In this snippet, if the variable arg is not null, the execution proceeds normally. If arg is null, then an assertion error is thrown: Exception in thread "main" java.lang.AssertionError at tips.AssertionTest.foo(AssertionTest.java:29) at tips.AssertionTest.main(AssertionTest.java:19) The second form of an assertion takes a Boolean expression and a second expression that will be passed as a message to the AssertionError object. ... assert (arg != null ) : "arg can not be null"; ... Now, if the assertion is false, the error will contain a message: Exception in thread "main" java.lang.AssertionError: arg can not be null at tips.AssertionTest.foo(AssertionTest.java:29) at tips.AssertionTest.main(AssertionTest.java:19) Assertions are a special part of the language, so when you use assertions you must use a special compiler switch, called the source option, to compile them: javac -source 1.4 AssertionTest.java The source switch takes a number indicating the version of Java with which the source compiles. If you don't use this option and your code contains assertions, you'll get an error like this: AssertionTest.java:29: warning: as of release 1.4, assert is a keyword, and may not be used as an identifier assert (arg != null ) : "arg can not be null"; ^ By default, assertions are disabled at runtime. Effectively, this means that your assertions will not be tested and no assertion errors will be thrown no matter what. This is normally how you'd run code with assertions in production. To enable assertions, you use the virtual machine command line switch -ea: java -ea tips.AssertionTest The -ea switch enables all assertions by default, but you can also enable assertions for a specific class or package. The -ea switch has a complementary disable assertions switch, -da, which works exactly like -ea but in reverse. ----------------------------------------