Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Java assert keyword do, and when should it be used?

What are some real life examples to understand the key role of assertions?

like image 656
Praveen Avatar asked May 03 '10 13:05

Praveen


People also ask

What is the use of assert keyword in Java?

assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError .

When should asserts be used in Java?

An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. It finds it application primarily in the testing purposes.

When should asserts be used?

Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.

Why do we need assertions in Java?

Assertions are used to codify the requirements that render a program correct or not by testing conditions (Boolean expressions) for true values, and notifying the developer when such conditions are false. Using assertions can greatly increase your confidence in the correctness of your code.


1 Answers

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 = null;   if (id > 50) {     result = fooService.read(id);   } else {     result = new Foo(id);   }   assert result != null;    return result; } 
like image 197
Ophidian Avatar answered Sep 19 '22 17:09

Ophidian