Usage of assertion
- to validate the program
We can use assertions on internal, control flow and class invariants as well to improve the programming experience.
Example
Scanner scanner = new Scanner( System.in );
System.out.print( "Enter a number between 0 and 20: " );
int value = scanner.nextInt();
assert( value >= 0 && value <= 20 ) :
System.out.printf( "You have entered %d\n", value );
To enable assertion at runtime , -ea option is used
java -ea AssertionExample
Output
Enter a number between 0 and 20: 4
You have entered 4
Enter a number between 0 and 20: 21
AssertionError will be thrwon by JVM
No comments:
Post a Comment
Note: only a member of this blog may post a comment.