Java assertion is an inbuilt statement that ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. Assertions in Java can be done with the help of the assert keyword.

Suppose there is a condition that you, as a programmer or a developer, while testing your code, want to make sure exists, such as making sure that a particular method shall  return only negative values; Java has a (relatively) new feature made available just for that.

The feature is called assertion, and wherein one can assert the existence of a particular condition. It is done with the help of the keyword assert. Assertions are generally used for testing and scarcely used in the release code. Release code is usually run with assertions disabled.

#Why to use Assertions

  1. We can make sure that an unreachable looking code is unreachable.
  2. We can make sure that assumptions written in the comments are right.
         if ((x & 1) == 1)  
         {  }
         else // x must be even 
         { assert (x % 2 == 0); }
  1. We can make sure the default switch case is not reached.
  2. We can check the object’s state.
  3. At the beginning of the method
  4. After the method invocation.

#assertion #java #assert

Assertion in Java Example | Java Assertion Tutorial
1.95 GEEK