HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

What are assertions in Java and when should they be used?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
javaassertionsareshouldandusedwhenwhatthey

Problem

What are some real life examples to understand the key role of the Java assert keyword?

Solution

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(int id) {
Foo result = (id > 50) ? fooService.read(id) : new Foo(id);

assert result != null;

return result;
}

Context

Stack Overflow Q#2758224, score: 506

Revisions (0)

No revisions yet.