The assert keyword is used in assert statement which is a feature of the Java programming language since Java 1.4. Assertion enables developers to test assumptions in their programs as a way to defect and fix bugs.
Syntax of assert statement:-
(short version):
assert expression1;
or (full version):
assert expression1 : expression2;
- expression1 must be a boolean expression.
- expression2 must return a value (must not return void).
By default,assertion is disabled at runtime to enable assertion,specify the switch -ea or
-enableassertions at command line of java program.for example to enable assertion for the program IsTest
java -enableassertions IsTest
or this for short
java -ea IsTest
1. You can combine switches to say disbale assertions in single class but keep enabled for all others.
java -ea -da:com.geekanonymous.Foo
the preceding command line tells the jvm keep the assertions enable in general and disable it for class Foo.
2. You can enable the assertion or disable the assertion in the System class with the -esa and -dsa flags.
3. if assertion statement is false then it will throw Assertion Error which you should never handle.
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0;
//assert ans>0 :"negative number";//give more information
System.out.println(ans);
}
}
}
No comments:
Post a Comment