Javatpoint Logo
Javatpoint Logo


Assertion is a statement in java. It can be used to test your assumptions about the program.

While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose.

Advantage of Assertion:

It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:

There are two ways to use assertion. First way is:

and second way is:

Simple Example of Assertion in java:

If you use assertion, It will not run simply because assertion is disabled by default. To enable the assertion, -ea or -enableassertions switch of java must be used.
Compile it by: javac
Run it by: java -ea AssertionExample
Output: Enter ur age 11
        Exception in thread "main" java.lang.AssertionError: Not valid

Where not to use Assertion:

There are some situations where assertion should be avoid to use. They are:

  1. According to Sun Specification, assertion should not be used to check arguments in the public methods because it should result in appropriate runtime exception e.g. IllegalArgumentException, NullPointerException etc.
  2. Do not use assertion, if you don't want any error in any situation.
Next TopicFor Each Loop

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA