Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
- assert <boolean expression>;
- 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.
- assert value > 5 ;
- assert accontBalance > 0;
- 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
- //AssertionDemo.java
- Class AssertionDemo{
- Public static void main(String args[]){
- System.out.println( withdrawMoney(1000,500) );
- System.out.println( withdrawMoney(1000,2000) );
- }
- public double withdrawMoney(double balance , double amount){
- assert balance >= amount;
- return balance – amount;
- }
- }
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 >>

check if the program executes
:)
Post new comment