Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :
Use J2SE 1.4.x (or later versions) to compile ExampleAssertions, make sure you use the -source option as follows:
javac -source 1.4 ExampleAssertions.java
If you try to compile your assertion-enabled classes without using the -source 1.4 option, you will get a compiler error saying that assert is a new keyword as of release 1.4. If you now run the program using the command 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.You have to enable assertions to make them work.Use the switch -enableassertion (or -ea) as follows:
java -ea ExampleAssertions
java -enableassertion ExampleAssertions
Following is a sample run:
When assertion fails it throws AssertionError.By default assertions are disabled but once enabled and you wnat to disable them then use switch -diableassertion (or -da).
Diabling assertions for a particular class in a package:
java -da:com.punsoft.acc.Account SavingAccount , this means running class SavingAccount with assertions of Account class disabled.
java -da:com.punsoft.acc... SavingAccount, this means running class SavingAccount with assertions of 'acc' package and its subpackages disabled.
You can use combination of enable and disable assertions.
java -ea:com.punsoft.acc... -da:com.punsoft.view.acc SavingAccountView
If you use the command
java -ea SavingAccount
then assertions are enabled in all classes except system classes. If you wish to turn assertions on or off in system classes, use the switches -enablesystemassertions (or -esa) and -disablesystemassertions (or -dsa).


0 comments:
Post a Comment