Assertion

Assertion: (Validation)

Assertion means simply validating the expected code in the given program. To test your assumptions while developing the code. Assertions are developing the environment. These are tested at the time of developing time.

How to write assumptions in java?

By using the “assert” we can write assumptions it is a keyword. It is introduced in ‘Java1.4’ version. It is there in ‘Java.lang’ package. Assertions are used to make sure that the expected value is there or not in the given program. We can write assertions in two ways

Syntax:

1.assert booleanExpression;(very simple way)

Ex:
					
assert true; //correct assert 0; // wrong because 0 is not Boolean value assert : true; // wrong because the syntax format is wrong assert (a>b&&b2); //correct

2.assert Expression: "Message"; (simple way)

Ex:
               
assert cost>0; // it doesnot print anything in the console assert cost>0 : “cost is not having desired value” +cost;

The above example shows it prints the console cost is not having proper value.

The result should be in Boolean value (true or false).

  • The assumption is true then the code will be executed after the assert statement.
  • If the assert is false then it throws an error that means assertions are not exceptions its an error.
  • We can give any number of expressions in assert statement but the coming result should be in boolean value only.
  • Assertions are used for the purpose of debugging.
  • In java assertions statements are by default disabled.
  • Assertions are meant for development environment only.
  • Once development stage is finished then assertions are not execute. If we want to run these assertions we should enable them.
Example program:
					
package practice; public class Asser { public static void main(String[] args) { int a = 55, b = 5; assert a > b; System.out.println(true); } }

How to enable assertions:

By using –ea we can enable the assertions

Ex:
      
Public class HelloWorld { Arguments ………………..; ………………..; }
To compile		: javac  HelloWorld.java
 To enable		: java –ea HelloWorld
 To disable     	        : java –da HelloWorld
	   

Why we are not using "if" condition rather than this:

If we use if & else condition if the ‘if’ condition fails then it goes to next statement i.e., else condition and continues the execution of program. But whereas by using assert it not continues the program if it fails the condition and come out from the execution of program. That is why we use this assert keyword.

assertions are used in switch cases i.e.,

Ex:
		
switch (ch) { case a: statements; break; case b: statements; break; default: assert false:”something frightful”; }

Use assertions only in the private methods and don’t use in the public methods. Assertions are enable or disable then the state of the object is not changed.

HTML Comment Box is loading comments...