ASSERTION

What is an assertion?
An assertion is a statement in Java that enables you to test your assumptions about your program.
Each assertion contains a boolean expression that you believe will be true when the assertion executes
By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
 
Why use assertions?
Programming by contract.
Pre-conditions:
Assert precondition as requirement of client.
Post-conditions:
Assert post-condition as effect of client method.
 
Simple Assertion Form
The assertion statement has two forms:
The first is: assert Expression 1 ;
Where Expression 1 is a boolean expression When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no details
 
Complex Assertion Form
The second form of the assertion statement is: assert Expression1 : Expression2 ;
where:
Expression 1 is a boolean expression.
Expression 2 is an expression that has a value.
It cannot invoke of a method that is declared void.
Use the second version of the assert statement to provide a detailed message for the AssertionError.
The system passes the value of Expression 2 to the appropriate Assertion Error constructor, which uses the string error message.
The purpose of the message is to communicate the reason for the assertion failure.
 
When an Assertion Fails
Assertion failures are labeled in stack trace with the file and line number from which they were thrown.
Second form of the assertion statement should be used in preference to the first when the program has some additional information that might help diagnose the failure.
 
Compiler Directives
For the javac compiler to accept code with assertions, use this command-line option: -source 1.4
For example:
javac -source 1.4 MyClass.java