Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Assertion, Java Assertion Classes

Java Assertion Assertion facility is added in J2SE 1.4. In order to support this facility J2SE 1.4 added the keyword assert to the language, and AssertionError class. An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime. Declaring Assertion Assertion statements have two forms as given below

  1. assert <boolean expression>;
  2. assert<boolean expression> : <expression2>;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime. If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime. Some examples that use simple assertion form are as follows.

  1. assert value > 5 ;
  2. assert accontBalance > 0;
  3. assert isStatusEnabled();

The expression that has to be asserted runtime must be boolean value. In third example isStatusEnabled() must return boolean value. If condition evaluates to true, execution continues normally, otherwise the AssertionError is thrown. Following Java Assertion Example program uses simple form of assertion

  1. //AssertionDemo.java
  2. Class AssertionDemo{
  3.  
  4. Public static void main(String args[]){
  5.  
  6. System.out.println( withdrawMoney(1000,500) );
  7. System.out.println( withdrawMoney(1000,2000) );
  8.  
  9. }
  10.  
  11. public double withdrawMoney(double balance , double amount){
  12.  
  13. assert balance >= amount;
  14. return balance &ndash; amount;
  15.  
  16. }
  17. }

In above given example, main method calls withdrawMoney method with balance and amount as arguments. The withdrawMoney method has a assert statement that checks whether the balance is grater than or equal to amount to be withdrawn. In first call the method will execute without any exception, but in second call it AssertionError is thrown if the assertion is enabled at runtime.


How To Enable Or Disable Assertion In Java >>
Your rating: None Average: 2 (1 vote)
Share this

Post new comment