What is the assert
keyword in Java?
Please tell me some real life examples to understand the key role of assertions?
What is the assert
keyword in Java?
Please tell me some real life examples to understand the key role of assertions?
A "real world example", from a Stack-class (from http://java.sun.com/developer/technicalArticles/JavaLP/assertions/)
public int pop() {
// precondition
assert !isEmpty() : "Stack is empty";
return stack[--num];
}
http://java.sun.com/developer/technicalArticles/JavaLP/assertions/
Assertions are used to check post-conditions and "should never fail" pre-conditions. Correct code should never fail an assertion; when they trigger, they should indicate a bug (hopefully at a place that is close to where the actual locus of the problem is).
An example of an assertion might be to check that a particular group of methods is called in the right order (e.g., that hasNext()
is called before next()
in an Iterator
).
Assertions helps developers write the java code that is more correct, more readable, and easier to maintain in future.
For more details of exapmle, see the following link.
Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea
option on the java
command, but are not turned on by default.
An example:
public Foo acquireFoo(Integer id) {
assert id != null && id > 0;
Foo result = null;
if (id > 50) {
result = fooService.read(id);
} else {
result = new Foo(id);
}
assert result != null;
return result;
}