Java Reference
In-Depth Information
Note that the
errorMessageExpression
in the second form of
assert
statement could be of any data type
excluding
void
. The above snippet of code provides x as the value of
errorMessageExpression
, which evaluates to an
int
. The runtime will use the string representation of the value of
x
when it throws an
AssertionError
.
At this point, you may be tempted to test the
assert
statement. Let's discuss some more details before you
compile and run Java classes with the
assert
statement. However, you will use Java code with an
assert
statement, as
shown in Listing 10-1.
Listing 10-1.
A Simple Test Class to Test the Assert Statement
// AssertTest.java
package com.jdojo.assertion;
public class AssertTest {
public static void main(String[] args) {
int x = 10 + 15;
assert x == 100:"x = " + x; // should throw an AssertionError
}
}
The code for the
AssertTest
class is simple. It assigns a value of 25 to the variable
x
and asserts that the value of
x
should be
100
. When you run the
AssertTest
class, you expect that it would always throw an
AssertionError
.
Testing Assertions
It is time to see
assert
statement in action. Try to run the
AssertTest
class using the following command:
java com.jdojo.assertion.AssertTest
This command finishes without any output. Did you not expect an error message on the standard output? Is your
assertion
x == 100
not false? The value of
x
is
25
, not
100
. You need to perform one more step before you can see the
assert
statement in action.
Try the following command to run the
AssertTest
class:
java -ea com.jdojo.assertion.AssertTest
This command generates the following output:
Exception in thread "main" java.lang.AssertionError: x = 25
at com.jdojo.assertion.AssertTest.main(AssertTest.java:7)
An
AssertionError
was generated with "
x = 25"
as the error message when you ran the
AssertTest
class.
This is what happens when an assertion fails in your code. The Java runtime throws an
AssertionError
. Because you
used the second form of the
assert
statement in your code, the error message also contains your custom assertion
message, which prints the value of
x
. Note that the assertion error, by default, contains the line number and the
source code file name where the assertion fails. The above error message states that the assertion failed at line 7 in the
AssertFile.java
source file.
So what is the magic behind using the
-ea
switch with the
java
command? By default,
assert
statements are not
executed by the Java runtime. In other words, the assertion is disabled by default. You must enable the assertion when
you run your class, so your
assert
statements are executed. The
-ea
switch enables the assertion at runtime. This is
the reason that you received the expected error message when you used the
-ea
switch to run the
AssertTest
class.
I will discuss enabling/disabling assertion in detail in the next section.