ProgrammingJava Developer

Describe how the assert mechanism works in Java. When should assert be used and how to use it properly?

Pass interviews with Hintsage AI assistant

Answer.

Background:

The assert mechanism was added in Java 1.4 to diagnose logical errors and developer assumptions within code. Assert allows detecting inconsistencies between expected and actual values at runtime without explicit thrown exceptions and does not appear in the final version of the application when assert support is turned off.

Problem:

Misusing assert instead of proper error checks (e.g., user input validation) and misunderstanding its disable-ability on a production server can lead to missed errors.

Solution:

Assert should be used only for logical invariants that cannot be violated during correct program operation, but if they are violated, the application behaves incorrectly.

Example code:

public int divide(int a, int b) { assert b != 0 : "Divider should not be zero!"; return a / b; }

Key features:

  • Assert can be disabled with JVM flags (-ea/–da), and then all asserts will be ignored
  • Assert should not be used for checking user or external data
  • The message after assert allows to explicitly state the reason for the failure

Tricky questions.

Will assert work by default when launching a Java program?

Answer: No, by default, assert is turned off. It must be explicitly enabled with the -ea flag (enable assertions).

Can assert be used in production code?

Answer: It is not recommended since AssertionError can be simply ignored. Using assert is possible only for invariants and in test code.

What is the difference between assert and throwing an exception?

Answer:

  • Assert is disabled in production environments, exceptions are not
  • Assert indicates a bug (invariant violated)
  • Exception is for handling expected errors

Common mistakes and anti-patterns

  • Using assert to validate user data
  • Using assert in code that should correctly handle an error, not just throw the stack

Real-life example

Negative case

A programmer uses assert to check the input data of a web application, allowing the user to trigger a critical error with incorrect values.

Pros:

  • Quickly implemented

Cons:

  • Assert is disabled on the production server, errors are not visible, data gets corrupted

Positive case

Assert is used only for internal invariants in the algorithm, while all checks for the user are done through ordinary exceptions.

Pros:

  • Explicit self-documenting code, errors are immediately visible during testing

Cons:

  • Assert does not always trigger in production, so duplicate control is needed for serious errors