To check or test your assumption in your code or program, assertion is used . For example , if you write a method for calculating the speed of a car , you can assert that calculated speed must be less than 100km/hr.
Given below the two forms of the assertion. The simple first form is :
assert BooleanExpression ;
In the above statement, system executes assertion statement and evaluate boolean expression and if it false, it throws exception AssertionError.
The second form of the assertion is :
assert BooleanExpression : Expression2 ;
Here Expression2 is an expression who has value or returns value, it can't be a void method.
Compiler accept your code having assertions, if you compile it as follows :
| javac ?source 1.4 DemoAssert.java |
The javac compiler accept your program, if you compile your .java file with -source 1.4 command-line option.
By default assertions are disabled at runtime. You can enable assertion at runtime as follows :
| java -ea DemoAssert |
OR
| java ?enableassertion DemoAssert |
You can disable assertion at runtime as follows :
| java -da DemoAssert |
OR
| java -disableassertions DemoAssert |
Given below a sample example to check the value must lie in between 0 & 20 :
import java.util.*;
import java.util.Scanner;
public class AssertionExample
{
public static void main( String args[] )
{
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 ) :
"Invalid number: " + value;
System.out.printf( "You have entered %d\n", value );
}
}
If you enter value in between 0 & 20, output should be :
| C:\>java -ea AssertionExample Enter a number between 0 and 20 : 4 You have entered 4 |
If you enter value greater than 20, For example 21, the following message will be displayed :
| C:\>java -ea AssertionExample Enter a number between 0 and 20 : 21 Exception in thread "main" java.lang.AssertionError: Invalid number: 21 at AssertionExample.main(AssertionExample.java:15) |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Assertion in Java
Post your Comment