Java Reference
In-Depth Information
While assertions can be stated as comments to guide you during program develop-
ment, Java includes two versions of the assert statement for validating assertions progra-
matically. The assert statement evaluates a boolean expression and, if false , throws an
AssertionError (a subclass of Error ). The first form of the assert statement is
assert expression ;
which throws an AssertionError if expression is false . The second form is
assert expression1 : expression2 ;
which evaluates expression1 and throws an AssertionError with expression2 as the error
message if expression1 is false .
You can use assertions to implement preconditions and postconditions programmati-
cally or to verify any other intermediate states that help you ensure that your code is
working correctly. Figure 11.8 demonstrates the assert statement. Line 11 prompts the
user to enter a number between 0 and 10, then line 12 reads the number. Line 15 deter-
mines whether the user entered a number within the valid range. If the number is out of
range, the assert statement reports an error; otherwise, the program proceeds normally.
1
// Fig. 11.8: AssertTest.java
2
// Checking with assert that a value is within range
3
import java.util.Scanner;
4
5
public class AssertTest
6
{
7
public static void main(String[] args)
8
{
9
Scanner input = new Scanner(System.in);
10
11
System.out.print( "Enter a number between 0 and 10: " );
12
int number = input.nextInt();
13
14
// assert that the value is >= 0 and <= 10
15
assert (number >= 0 && number <= 10 ) : "bad number: " + number;
16
17
System.out.printf( "You entered %d%n" , number);
18
}
19
} // end class AssertTest
Enter a number between 0 and 10: 5
You entered 5
Enter a number between 0 and 10: 50
Exception in thread "main" java.lang.AssertionError: bad number: 50
at AssertTest.main(AssertTest.java:15)
Fig. 11.8 | Checking with assert that a value is within range.
You use assertions primarily for debugging and identifying logic errors in an applica-
tion. You must explicitly enable assertions when executing a program, because they reduce
 
Search WWH ::




Custom Search