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

Assertions are checks which may get switched off. They're rarely used. Why?

  • They must not be used for checking public method arguments as you have no control over them.
  • They should not be used for simple checks like result != null as such checks are very fast and there's hardly anything to save.

So, what's left? Expensive checks for conditions really expected to be true. A good example would be the invariants of a data structure like RB-tree. Actually, in ConcurrentHashMap of JDK8, there are a few such meaningful asserts for the TreeNodes.

  • You really don't want to switch them on in production as they could easily dominate the run time.
  • You may want to switch them on or off during tests.
  • You definitely want to switch them on when working on the code.

Sometimes, the check is not really expensive, but at the same time, you're pretty sure, it'll pass. In my code, there's e.g.,

assert Sets.newHashSet(userIds).size() == userIds.size();

where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it.