views:

170

answers:

4
+4  Q: 

Assertion in Java?

What is the assert keyword in Java?

Please tell me some real life examples to understand the key role of assertions?

+2  A: 

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/

Björn
This would be frowned upon in C: An assertion is something that REALLY NEVER should happen - popping an empty stack should throw a NoElementsException or something along the lines. See Donal's reply.
Konerak
I agree. Even though this is taken from an official tutorial, it's a bad example.
DJClayworth
+2  A: 

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).

Donal Fellows
You don't have to call hasNext() before next().
DJClayworth
@DJClayworth: You don't need to avoid triggering assertions either. :-)
Donal Fellows
+1  A: 

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.

Assertion Example

Venkats
+5  A: 

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;
}
Ophidian