Let Us Know about Assertions In Java


This resource contains the information about assertions in java with example etc.

Let Us Know about Assertions In Java



Assertions are used during program development to create an assertion, which is a condition that should be true during the execution of the program.
For example, you might have a method that should always return a positive integer value. You might test by asserting that the return value is greater than zero using an assert statement. At run time, if the condition is actually is true, no other action takes place. However, if the condition is false, then a AssertionError is thrown. Assertions are often used during testing to verify that some expected condition is actually true. They are not usually used for released code.
Syntax: assert condition;

To enable assertion checking at runtime, you must specify the -ea option.
Example: java -ea AssertDemo

To disable assertion checking at runtime, you must specify the -da option.
Example: java -da AssertDemo


AssertDemo.java

class AssertDemo
{
int val=3;
int getnum()
{
return val--;
}
public static void main(String args[])
{
int n;
for(int i=0;i<10;i++)
{
n=getnum();
assert n>0; // will fail when n is 0
System.out.println("n is "+n);
}
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: