Assertion:
Assertion is a statement used to test assumptions of the programmer about the program. While, executing assertion it is always true but in case , it fails, JVM will throw an error named AssertionError. Assertion is mainly used for testing purpose.
Implementation of assertion:
To implement assertion, "assert" keyword is used.
Syntax: assert booleanExpression;
Advantages of Assertion:
- Data validation.
- It helps to detect bug early in development cycle which is very cost effective
- It will help you to be better programmer and improve code quality.
- You can create new code and use assertion to compare output with old method.
There are some situations where assertion should be avoid to use. They are:
Assertion create a runtime exception while we check arguments in public methods e.g. IllegalArgumentException, NullPointerException etc.
Do not use assertion, if you don't want any error in any situation.
import java.util.Scanner;
class AssertionExample{
public static void main( String args[] ){
Scanner scanner = new Scanner( System.in );
System.out.print("Enter ur age ");
int value = scanner.nextInt();
assert value>=20:" Not valid";
System.out.println("value is "+value);
}
}
0 Comment(s)