Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: J2SE 1.4 premieres Java's assertion capabilities, Part 1

J2SE 1.4 premieres Java's assertion capabilities, Part 1

Tutorial Details:

J2SE 1.4 premieres Java's assertion capabilities, Part 1
J2SE 1.4 premieres Java's assertion capabilities, Part 1
By: By Wm. Paul Rogers
Understand the mechanics of Java's new assertion facility
ssertions have been in the software engineering canon for many years, most notably as the centerpiece of the Design by Contract facility that Bertrand Meyer built into his Eiffel programming language. Assertions date back at least as far as the 1967 article "Assigning Meanings to Programs" ( Proceedings of the Symposium on Applied Mathematics, Vol. 19, pp. 19-32; American Mathematical Society, 1967), in which Robert Floyd discussed using assertions to systematically prove program correctness. Correctness pertains to a system's adherence to a specification and complements the other major reliability attribute, robustness, which pertains to a system's ability to handle abnormal conditions.
As I will explain in Part 2 of this series, assertions help implement correct programs. Assertions were actually part of Oak, an early version of Java, but were jettisoned in a final push to get Java out of the lab and into the hands of Internet developers. As part of the Java Community Process, Java Specification Request 41 proposed adding a simple assertion facility to Java, prompting its welcome reappearance in J2SE (Java 2 Platform, Standard Edition) version 1.4.
An assertion is a boolean expression that a developer specifically proclaims to be true during program runtime execution. The simple idea of using assertions can have an unexpected influence on a software program's design and implementation. In this article I cover the mechanics of using the new assertion facility introduced in J2SE 1.4. In Part 2 I will cover the methodology of using assertions.
Read the whole series on J2SE 1.4's assertion capabilities:
Part 1: Understand the mechanics of Java's new assertion facility
Part 2: Understand the methodology impact of Java's new assertion facility
Declare an assertion
You declare assertions with a new Java language keyword, assert . An assert statement has two permissible forms:
assert expression 1 ;
assert expression 1 : expression 2 ;
In each form, expression 1 is the boolean-typed expression being asserted. The expression represents a program condition that the developer specifically proclaims must be true during program execution. In the second form, expression 2 provides a means of passing a String message to the assertion facility. The following are a few examples of the first form:
assert 0 < value;
assert ref != null;
assert count == (oldCount + 1);
assert ref.m1(parm);
The asserted expression must be of type boolean , which the first three expressions obviously are. In the fourth expression, the method call m1(parm) must return a boolean result. A compile-time error occurs if expression 1 does not evaluate to type boolean .
As an example of using assertions, class Foo listed below contains a simple assertion in the method m1(int) :
public class Foo
{
public void m1( int value )
{
assert 0 <= value;
System.out.println( "OK" );
}
public static void main( String[] args )
{
Foo foo = new Foo();
System.out.print( "foo.m1( 1 ): " );
foo.m1( 1 );
System.out.print( "foo.m1( -1 ): " );
foo.m1( -1 );
}
}
The method main() calls m1(int) twice, once with a positive value and once with a negative value. The call with the negative value triggers an assertion error. Since assert is a new Java keyword, to see this example in action, you must compile the class with a J2SE 1.4-compliant compiler. Furthermore, the compiler requires a command-line option, -source 1.4 , to signal source compilation using the assertion facility. Requiring a command-line switch to include assertions purportedly protects backward compatibility.
By default (that is, in the absence of the -source 1.4 switch), a J2SE 1.4 compiler does not allow assert statements. However, the compiler complains if the source code uses the assert keyword as an identifier or label. That means a J2SE 1.4 compiler rejects prior Java source files that use assert in this manner, even though the source compiled successfully under J2SE 1.3 or an earlier compiler. Note that this does not affect previously compiled class files.
The following command compiles Foo.java :
javac -source 1.4 Foo.java
The resulting Foo.class file contains assertion code in the method m1(int) . But, just as the compiler does not, by default, include the assertion facility, the java command does not, by default, enable assertions. In other words, assertions are disabled in the Java runtime environment by default.
The default behavior of the compiler and runtime system seems backward to me. Assertions are an important enough addition to the Java language that they should be included and enabled by default. The compile-line option should be -source 1.3 for the backward compatibility of not including the assertion facility, and the java command should enable assertions by default. I appreciate the pressure to preserve backward compatibility, but assertions prove too important to be relegated to a special, nondefault case. But I'll get off my soapbox now and continue.
Enable assertions
Command-line options to the java command allow enabling or disabling assertions down to the individual class level. The command-line switch -enableassertions , or -ea for short, enables assertions. The switch (I use the short form) has the following permissible forms:
-ea
-ea:
-ea:...
-ea:...
The first form enables assertions in all classes except system classes. A separate switch, -enablesystemsassertions , or -esa for short, enables system class assertions. System classes warrant a separate switch because developers rarely have occasion to suspect assertion errors in the Java system libraries.
The second form turns on assertions for the named class only. The last two forms enable assertions at the package level. The third enables assertions for the default, or unnamed, package, and the fourth enables assertions for the specified package name.
Take care in using the second and fourth forms, since class and package names are not verified for existence. As we'll see later in this article, the class ClassLoader maintains a mapping of class and package names to desired assertion status. When a ClassLoader subclass loads a class, the mappings determine the setting of a special assertions-enabled flag in each class. Any mappings for nonexistent classes or packages are simply never accessed. In particular, the runtime system silently interprets a package name without a trailing " ... " as a class name.
Note that the syntax for enabling assertions at the package level uses ... rather than the expected * . The trailing ... serves as reminder of another assertion facility aspect: enabling assertions at the package level actually turns on assertions for that package and all subpackages. For example, the command-line switch -ea:javax.swing... enables assertions for all Swing packages, and the command-line switch -ea:javax.xml... enables assertions for the five J2SE 1.4 XML packages. Interestingly, in the latter example the five XML packages are considered javax.xml subpackages even though javax.xml is not, itself, a package.
The following shows the result of running Foo with the command java Foo , in which the default runtime environment disables assertion checking:
foo.m1( 1 ): OK
foo.m1( -1 ): OK
With assertions disabled, neither m1(int) method call triggers an assertion. As previously described, enabling assertion requires the use of a command-line switch. Any of the following commands enables assertion checking in class Foo :
java -ea Foo
java -ea:Foo Foo
java -ea:... Foo
The following shows the resulting output:
foo.m1( 1 ): OK
foo.m1( -1 ): Exception in thread "main" java.lang.AssertionError
at Foo.m1(Foo.java:6)
at Foo.main(Foo.java:17)
Calling method m1(int) with the parameter 1 fails to trigger the assertion. However, passing -1 violates the assertion that the parameter must be a positive integer. The Java runtime system reports the failed assertion through the use of a new class, java.lang.AssertionError .
Class AssertionError
The new assertion facility adds the class AssertionError to the java.lang package. AssertionError contains a default constructor and seven single-parameter constructors. The assert statement's single-expression form uses the default constructor, whereas the two-expression form uses one of the seven single-parameter constructors.
To understand which AssertionError constructor is used, consider how assertions are processed when enabled:
Evaluate expression 1
If true
No further action
If false
And if expression 2 exists
Evaluate expression 2 and use the result in a single-parameter form of the AssertionError constructor
Else
Use the default AssertionError constructor
Since the assert statement in class Foo uses the single-expression form, the violation triggered in passing -1 to method m1(int) prompts the use of the default AssertionError constructor. The default constructor effectively uses java.lang.Throwable 's default constructor to print an exception message that includes a textual stack trace description.
The assertion error output from running class Foo is lacking. We see that an AssertionError occurs in method m1 at line 6 , but the output does not describe what went wrong. Fortunately, the assert statement's two-expression form provides this facility. As noted above, in the two-expression form, when expression 1 evaluates as false , the assertion facility passes the result of evaluating expression 2 to a single-parameter AssertionError constructor. Expression 2 effectively acts as a String message carrier, meaning AssertionError 's single-parameter constructors must convert the result of expression 2 to a String . Covering all expression result-type possibilities requires a separate constructor for each


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
J2SE 1.4 premieres Java's assertion capabilities, Part 1

View Tutorial:
J2SE 1.4 premieres Java's assertion capabilities, Part 1

Related Tutorials:

Java security evolution and concepts, Part 1: Security nuts and bolts - JavaWorld April 2000
Java security evolution and concepts, Part 1: Security nuts and bolts - JavaWorld April 2000
 
J2SE 1.4 premieres Java's assertion capabilities, Part 1
J2SE 1.4 premieres Java's assertion capabilities, Part 1
 
J2SE 1.4 premieres Java's assertion capabilities, Part 2
J2SE 1.4 premieres Java's assertion capabilities, Part 2
 
Java security evolution and concepts, Part 5
Java security evolution and concepts, Part 5
 
Implement Design by Contract for Java using dynamic proxies
Implement Design by Contract for Java using dynamic proxies
 
Trace your steps in Java 1.4
Trace your steps in Java 1.4
 
Discover and publish Web services with JAXR
Discover and publish Web services with JAXR
 
J2SE 1.4 breathes new life into the CORBA community, Part 1
J2SE 1.4 breathes new life into the CORBA community, Part 1
 
All that JAAS
All that JAAS
 
J2SE 1.4 breathes new life into the CORBA community, Part 2
J2SE 1.4 breathes new life into the CORBA community, Part 2
 
J2SE 1.4 breathes new life into the CORBA community, Part 3
J2SE 1.4 breathes new life into the CORBA community, Part 3
 
J2SE 1.4 breathes new life into the CORBA community, Part 4
J2SE 1.4 breathes new life into the CORBA community, Part 4
 
Overcome J2SE 1.3-1.4 incompatibilities
Overcome J2SE 1.3-1.4 incompatibilities
 
Good, but obsolete
Good, but obsolete
 
Taming Tiger
Taming Tiger, Part 2 Understanding generics Welcome to the second part of this three-part series on Sun Microsystems' latest release of the Java 2 Platform, Standard Edition (J2SE). To refresh your memory, Part 1 was a quick introduction to J2SE 1.5
 
From Writing Programs to Creating Compilers
From Writing Programs to Creating Compilers In this article we build a simple compiler that augments Java with tasks (independent blocks of code that execute in parallel), thus creating a new language called AJ that well supports the programming of syste
 
Network Programming with JavaTM 2 Platform, Standard Edition 1.4 (J2SETM)
This article provides an overview of the new features and enhancements in the Java 2 Platform, Standard Edition 1.4 (J2SE), and shows you how to use them effectively.
 
Pure Java SSH Tool for J2ME
JSch is the pure Java SSH2 implementation developed by JCraft under revised BSD license. It has been already widely adopted by several open source projects, including Eclipse, Apache Ant, etc.,
 
NetBeans IDE 4.1
Out-of-the-box support for J2EE 1.4 and Web Services. Check out what early access release 2 can do for you!
 
J2SE Platform Migration Guide (pdf)
This guide helps developers migrate Java applets, standalone applications, Java Web Start applications and development tools from version 1.3 and 1.4 of the Java platform to version 5.0.
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.